.Continue starts before task is completed
When you pass an async
delegate to Task.Factory.StartNew
, the returned Task
only represents the first portion of that delegate (up until the time it await
s something that is not already completed).
However, if you pass an async
delegate to the new Task.Run
method (which was included for this reason), the returned Task
represents the entire delegate. So you can use ContinueWith
as you expect. (Although await
is usually a better option than ContinueWith
).
For more information on StartNew
vs Run
, see Stephen Toub's post on the topic.
The await will immediately return control to the calling function, which in this case is the StartNew of your task. This means the task will then complete and execute the ContinueWith.If you really want task to complete before the ContinueWith, then don't await the Task.Delay.
I saw this in the MSDN: :-)
public async void button1_Click(object sender, EventArgs e){ pictureBox1.Image = await Task.Run(async() => { using(Bitmap bmp1 = await DownloadFirstImageAsync()) using(Bitmap bmp2 = await DownloadSecondImageAsync()) return Mashup(bmp1, bmp2); });}
So do not forget the "async()" !!!