by Corrado Cavalli via Corrado's BLogs on 10/25/2011 7:16:28 AM
In WinRT any method that takes more than 50 ms is exposed as an asyncronous operation and thanks to C# await keyword (or Javascript’s Promises) what could be a programmer’s headache becomes a straightforward task, but what if you have your own asyncronous code? Let’s say you have a basic downloader class that simulates downloading a string from the internet, in practice something like:
public class MyDownloader{ public event EventHandler Completed; public string Result { get; set; } public void Download() { TimeSpan delay = TimeSpan.FromMilliseconds(1000); var timer = ThreadPoolTimer.CreateTimer((tpt) => { this.Result = DateTime.Now.Ticks.ToString(); this.Completed(this, EventArgs.Empty); } , delay); } }
private void Button_Click(object sender, RoutedEventArgs e){ MyDownloader downloader = new MyDownloader(); downloader.Completed += (s, a) => { this.Dispatcher.Invoke(Windows.UI.Core.CoreDispatcherPriority.Normal, (t, o) => tb1.Text = downloader.Result,this,null); }; downloader.Download();}
public Task<string> DownloadAsync(){ TaskCompletionSource<string> taskCompletionSource = new TaskCompletionSource<string>(); this.Completed += (s, a) => { taskCompletionSource.SetResult(this.Result); //SetException }; this.Download(); return taskCompletionSource.Task;}
async private void Button_Click2(object sender, RoutedEventArgs e) { MyDownloader downloader = new MyDownloader(); tb1.Text= await downloader.DownloadAsync(); }
Original Post: WinRT Pills: Make your own Async methods
The content of the postings is owned by the respective author. Silverlight Feeds is not responsible for the contents of the postings. This site is automatically generated and cannot be reviewed for abusive content. If you find abusive content on Silverlight Feeds, please contact us. Designated trademarks and brands are the property of their respective owners. All rights reserved.