C# winform中使用IAsyncResult实现异步编程

using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; using System.Runtime.Remoting.Messaging; namespace AsyncCall { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private delegate int MyAsyncDelegate(); private void button1_Click(object sender, EventArgs e) { this.progressBar1.Value = 0; this.progressBar1.Maximum = 1000000; this.progressBar1.Step = 10; MyAsyncDelegate del = new MyAsyncDelegate(DoAsyncEvent); IAsyncResult result = del.BeginInvoke(new AsyncCallback(CallBack), null); } ///

/// 执行方法 /// /// private int DoAsyncEvent() { try { while (this.progressBar1.Value < this.progressBar1.Maximum) { this.progressBar1.PerformStep(); } return 1; } catch { return -1; } } /// /// 回调函数得到异步线程的返回结果 /// /// private void CallBack(IAsyncResult iasync) { AsyncResult async = (AsyncResult)iasync; MyAsyncDelegate del = (MyAsyncDelegate)async.AsyncDelegate; int iResult = del.EndInvoke(iasync); if (iResult>0) { MessageBox.Show(string.Format("异步操作完成,返回结果为:{0}.",iResult)); } } /// /// 线程访问控件 /// /// /// private void Form1_Load(object sender, EventArgs e) { Control.CheckForIllegalCrossThreadCalls = false; } } }

 

 

 

 

经过改进后:

 

 using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Runtime.Remoting.Messaging; namespace AsyncCall { public class AsyncEvent { ///

/// 声明委托 /// /// /// public delegate T MyAsyncDelegate(); public delegate T MyAsyncDelegate2(int a, int b); /// /// 回调函数得到异步线程的返回结果 /// /// public static T CallBack(IAsyncResult iasync) { AsyncResult async = (AsyncResult)iasync; MyAsyncDelegate del = (MyAsyncDelegate)async.AsyncDelegate; return (T)del.EndInvoke(iasync); } } }

using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; using System.Runtime.Remoting.Messaging; namespace AsyncCall { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void button1_Click(object sender, EventArgs e) { this.progressBar1.Value = 0; this.progressBar1.Maximum = 1000000; this.progressBar1.Step = 10; AsyncEvent.MyAsyncDelegate del = new AsyncEvent.MyAsyncDelegate(DoAsyncEvent); IAsyncResult result = del.BeginInvoke(new AsyncCallback(CallBack), null); } ///

/// 回调函数得到异步线程的返回结果 /// /// public void CallBack(IAsyncResult iasync) { if (AsyncEvent.CallBack(iasync) > 0) { MessageBox.Show("成功"); } } /// /// 执行方法 /// /// private int DoAsyncEvent() { try { while (this.progressBar1.Value < this.progressBar1.Maximum) { this.progressBar1.PerformStep(); } return 1; } catch { return -1; } } /// /// 线程访问控件 /// /// /// private void Form1_Load(object sender, EventArgs e) { Control.CheckForIllegalCrossThreadCalls = false; } } }

 

 

 

你可能感兴趣的:(.NET,FrameWork)