Consider the following code:
Task task1;
Task task2;
private void button1_Click(object sender, EventArgs e)
{
task1 = Task.Run(() =>
{
for (int i = 0; i < 100000; i++)
{
BeginInvoke(new Action<int>((int n) =>
{
listView1.Items.Add(n.ToString());
}), i);
}
});
task2 = task1.ContinueWith(t =>
{
MessageBox.Show("Why isn't this reached");
}, TaskScheduler.FromCurrentSynchronizationContext());
}
private void button2_Click(object sender, EventArgs e)
{
MessageBox.Show(String.Format("task1 status:{0}\r\ntask2 status:{1}", task1.Status, task2.Status));
}
If I run this on Windows 8, .NET Framework 4.5.2, I get the follwing output when I click button2:
task1 status:RanToCompletion
task2 status:WaitingToRun
How is this possible even though I used ContinueWith?
I know that BeginInvoke just enqueues the delegate for execution, if I use Invoke it works just fine. Is this a bug or is it interfering with BeginInvoke? Any ideas? Thanks in advance.