Form1.cs 2.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. using System;
  2. using System.Collections.Generic;
  3. using System.ComponentModel;
  4. using System.Data;
  5. using System.Drawing;
  6. using System.Linq;
  7. using System.Text;
  8. using System.Threading.Tasks;
  9. using System.Windows.Forms;
  10. namespace DomeApp
  11. {
  12. public partial class Form1 : Form
  13. {
  14. public Form1()
  15. {
  16. InitializeComponent();
  17. }
  18. //创建一个委托,是为访问DataGridVie控件服务的。
  19. public delegate void UpdateControl();
  20. delegate string AsyncMethodCaller();
  21. private void button1_Click(object sender, EventArgs e)
  22. {
  23. AsyncMethodCaller caller = new AsyncMethodCaller(TestMethod);
  24. for (int i = 0; i < 10000; i++)
  25. {
  26. IAsyncResult result = caller.BeginInvoke(GetResult, null);
  27. }
  28. this.label1.Text = "OK";
  29. /* var t = Task.Factory.StartNew(() =>
  30. {
  31. for (int i = 0; i < 10000; i++)
  32. {
  33. this.label1.Invoke(new UpdateControl(delegate ()
  34. {
  35. this.label1.Text = (i++).ToString();
  36. }));
  37. }
  38. });
  39. t.Wait();*/
  40. /* for (int i = 0; i < 10000; i++)
  41. {
  42. await Task.Factory.StartNew(() =>
  43. {
  44. for (int j = 0; j < 100; j++)
  45. {
  46. System.Threading.Thread.Sleep(1);
  47. }
  48. });
  49. this.label1.Text = (i++).ToString();
  50. }
  51. */
  52. }
  53. #region 使用APM实现异步编程
  54. // 同步方法
  55. private string TestMethod()
  56. {
  57. // 模拟做一些耗时的操作
  58. // 实际项目中可能是读取一个大文件或者从远程服务器中获取数据等。
  59. for (int i = 0; i < 1000; i++)
  60. {
  61. System.Threading.Thread.Sleep(1);
  62. }
  63. return "事件完成";
  64. }
  65. // 回调方法
  66. private void GetResult(IAsyncResult result)
  67. {
  68. AsyncMethodCaller caller = (AsyncMethodCaller)((System.Runtime.Remoting.Messaging.AsyncResult)result).AsyncDelegate;
  69. // 调用EndInvoke去等待异步调用完成并且获得返回值
  70. // 如果异步调用尚未完成,则 EndInvoke 会一直阻止调用线程,直到异步调用完成
  71. string resultvalue = caller.EndInvoke(result);
  72. //sc.Post(ShowState,resultvalue);
  73. this.label1.Invoke(new UpdateControl(delegate ()
  74. {
  75. this.label1.Text = resultvalue+":"+DateTime.Now.ToString("HHmmsssfff");
  76. }));
  77. //richTextBox1.Invoke(showStateCallback, resultvalue);
  78. }
  79. #endregion
  80. }
  81. }