using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace DomeApp { public partial class Form1 : Form { public Form1() { InitializeComponent(); } //创建一个委托,是为访问DataGridVie控件服务的。 public delegate void UpdateControl(); delegate string AsyncMethodCaller(); private void button1_Click(object sender, EventArgs e) { AsyncMethodCaller caller = new AsyncMethodCaller(TestMethod); for (int i = 0; i < 10000; i++) { IAsyncResult result = caller.BeginInvoke(GetResult, null); } this.label1.Text = "OK"; /* var t = Task.Factory.StartNew(() => { for (int i = 0; i < 10000; i++) { this.label1.Invoke(new UpdateControl(delegate () { this.label1.Text = (i++).ToString(); })); } }); t.Wait();*/ /* for (int i = 0; i < 10000; i++) { await Task.Factory.StartNew(() => { for (int j = 0; j < 100; j++) { System.Threading.Thread.Sleep(1); } }); this.label1.Text = (i++).ToString(); } */ } #region 使用APM实现异步编程 // 同步方法 private string TestMethod() { // 模拟做一些耗时的操作 // 实际项目中可能是读取一个大文件或者从远程服务器中获取数据等。 for (int i = 0; i < 1000; i++) { System.Threading.Thread.Sleep(1); } return "事件完成"; } // 回调方法 private void GetResult(IAsyncResult result) { AsyncMethodCaller caller = (AsyncMethodCaller)((System.Runtime.Remoting.Messaging.AsyncResult)result).AsyncDelegate; // 调用EndInvoke去等待异步调用完成并且获得返回值 // 如果异步调用尚未完成,则 EndInvoke 会一直阻止调用线程,直到异步调用完成 string resultvalue = caller.EndInvoke(result); //sc.Post(ShowState,resultvalue); this.label1.Invoke(new UpdateControl(delegate () { this.label1.Text = resultvalue+":"+DateTime.Now.ToString("HHmmsssfff"); })); //richTextBox1.Invoke(showStateCallback, resultvalue); } #endregion } }