I/O should use async, asynchronous method can be achieved:
message, delegate, multi-threading
Thread-safe
1. private void button_Click(object sender, EventArgs e) 2. { 3. var task = new Task(() => 4. { 5. this.lblResult.Invoke(new Action (() => { 6. this.lblResult.Text = DateTime.Now.ToLongTimeString(); 7. })); 8. }); 9. task.Start(); 10. }
Before async/await
1. private void button_Click(object sender, EventArgs e) 2. { 3. this.lblResult.Text = "starting to ..."; 4. var compute = new Func(i => 5. { 6. long result = 1; 7. 8. for (int n = 0; n <= i; n++) 9. { 10. result += 1; 11. } 12. 13. return result.ToString(); 14. }); 15. 16. compute.BeginInvoke(int.MaxValue / 2, new AsyncCallback(ar => 17. { 18. #region 21. //this.lblResult.Text = compute.EndInvoke(ar); 22. #endregion 23. 24. this.lblResult.Invoke(new MethodInvoker(() => 25. this.lblResult.Text = compute.EndInvoke(ar))); 26. } 27. ), new object()); 28. }
After aync/await
1. public long DoSomething(int n) 2. { 3. long result = 1; 4. 5. for (int i = 0; i <= n; i++) 6. { 7. result += 1; 8. } 9. 10. return result; 11. } 12. private async void button_Click(object sender, EventArgs e) 13. { 14. this.lblResult.Text = "staring to ..."; 15. var value = await DoSomethingAsync(int.MaxValue / 2); 16. this.lblResult.Text = value.ToString(); 17. } 18. private TaskDoSomethingAsync(int n) 19. { 20. return Task.Run (() => DoSomething(n)); 21. }