Created
September 20, 2016 23:41
-
-
Save fliedonion/d2816619c68915188e3b118998245772 to your computer and use it in GitHub Desktop.
TaskCompletionSource example.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Program { | |
static Task<byte[]> FromWebClient(WebClient wc, Uri address) { | |
var tcs = new TaskCompletionSource<byte[]>(); | |
wc.DownloadDataCompleted += (object sender, DownloadDataCompletedEventArgs e) => { | |
if (e.Cancelled) | |
tcs.SetCanceled(); | |
else if (e.Error != null) | |
tcs.SetException(e.Error); | |
else | |
tcs.SetResult(e.Result); | |
}; | |
wc.DownloadDataAsync(address); | |
return tcs.Task; | |
} | |
static void Main(string[] args) { | |
Task<int> f = Task.Factory.StartNew(() => { | |
return 42; | |
}); | |
Task<byte[]> t = FromWebClient(new WebClient(), new Uri("http://www.bing.com")); | |
// t.Wait(); | |
t.ContinueWith(doneData => { | |
var data = doneData.Result; | |
var str = Encoding.UTF8.GetString(data); | |
Console.WriteLine(str.Substring(0, 50)); | |
}); | |
Console.WriteLine("after task."); | |
Console.ReadKey(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment