Skip to content

Instantly share code, notes, and snippets.

@fliedonion
Created September 20, 2016 23:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save fliedonion/d2816619c68915188e3b118998245772 to your computer and use it in GitHub Desktop.
Save fliedonion/d2816619c68915188e3b118998245772 to your computer and use it in GitHub Desktop.
TaskCompletionSource example.
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