1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 | using System; using System.Windows.Forms; using System.Threading; using System.Threading.Tasks; namespace TestAsync { public partial class Form1 : Form { public Form1() { InitializeComponent(); } // inherently synchrononous operation public int ComputeSomething( int n) { // Problem is O(N) while (n-- > 0) Thread.Sleep(1000); return 7; } // Wrap the synchronous operation on Task-based Async Pattern to make the operation operate asynchronously Task< int > ComputeSomethingAsync( int n) { Task< int > t = new Task< int >(() => { return ComputeSomething(n); }); t.Start(); return t; } private void button1_Click( object sender, EventArgs e) { // instead of doing things synchronously if ( false ) { int n = ComputeSomething(10); MessageBox.Show( "Returned value is " + n.ToString()); } // do things asynchronously instead if ( true ) { Task< int > t = ComputeSomethingAsync(10); t.ContinueWith(x => { if (x.IsFaulted) { MessageBox.Show(x.Exception.Message); } else { MessageBox.Show( "Returned value is " + x.Result.ToString()); } }); } } //button1_Click } //class Form1 } |
For asynchronous operation, TAP asynchronous design pattern is easier to use than BeginXXX, EndXXX, IAsyncResult combo async pattern
On next C# version(C# 5), making routines asynchronous will be a lot easier with its built-in await and async functionality
No comments:
Post a Comment