C# 多线程 与 委托
生活随笔
收集整理的這篇文章主要介紹了
C# 多线程 与 委托
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
簡單的多線程:
protected void Page_Load(object sender, EventArgs e){ParameterizedThreadStart _ParameterizedThreadStart = new ParameterizedThreadStart(MyMethod);Thread t = new Thread(_ParameterizedThreadStart);object o = "sdfsf";t.Start(o);}private void MyMethod(object o){//執行任務}
使用委托的多線程:
public partial class Demo : Form{public Demo(){InitializeComponent();}//定義委托delegate void MyDelegate(string str);//聲明委托 MyDelegate _MyDelegate;//聲明線程private Thread t;private void Demo_Load(object sender, EventArgs e){//給函數指定委托_MyDelegate = new MyDelegate(SetLblTxt);}//執行委托private void Run(){while (true){lblShow.Invoke(_MyDelegate, new object[] { Guid.NewGuid().ToString() });Thread.Sleep(100);}}//設定lable的textprivate void SetLblTxt(string o){this.lblShow.Text = o.ToString();}private void btnBegin_Click(object sender, EventArgs e){t = new Thread(new ThreadStart(Run));t.Start();}private void Demo_FormClosing(object sender, FormClosingEventArgs e){//終止線程if (t.IsAlive) {t.Abort(); }}}?有返回值的多線程:
//定義委托delegate string MyDelegate(string str);//聲明委托 MyDelegate _MyDelegate;//聲明線程private Thread t;private void Demo_Load(object sender, EventArgs e){//給函數指定委托_MyDelegate = new MyDelegate(SetLblTxt);}//執行委托private void Run(){object o = new object();while (true){lock (lblShow){//lblShow.Invoke(_MyDelegate, new object[] { Guid.NewGuid().ToString() }); //其實是同步調用IAsyncResult result = lblShow.BeginInvoke(_MyDelegate, new object[] { Guid.NewGuid().ToString() }); //異步調用MessageBox.Show(lblShow.EndInvoke(result).ToString()); //獲得返回值Thread.Sleep(1000);}}}//設定lable的textprivate string SetLblTxt(string o){this.lblShow.Text = o.ToString();return o.ToString();}private void btnBegin_Click(object sender, EventArgs e){t = new Thread(new ThreadStart(Run));t.Start();}private void Demo_FormClosing(object sender, FormClosingEventArgs e){//終止線程if (t == null) return;if (t.IsAlive) {t.Abort(); }}?
轉載于:https://www.cnblogs.com/wugang/archive/2013/02/27/2934632.html
總結
以上是生活随笔為你收集整理的C# 多线程 与 委托的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 64位进程调用32位dll的解决方法 /
- 下一篇: Nuget常用命令(转)