I am building an ASP.NET application using WPF with a long-running asynchronous Task that, in some cases, needs to ask the user for some more info. Is there a way I could interrupt, but not cancel, the task, wait for the user to respond and continue based on the result?
All I have found are ways to use callbacks before and after the task. I have tried invoking UI thread methods via Send() of a SynchronizationContext passed from the main thread, but it (sometimes) throws Null Reference Exception.
To be more specific, I am unable to understand why this code throws NullReferenceException when it calls Send():
protected void Page_Load(object sender, EventArgs e)
{
Task task = new Task(DoSomeWork, new Tuple<SynchronizationContext, object>(SynchronizationContext.Current, new object()));
task.Start();
}
public void DoSomeWork(object state)
{
Tuple<SynchronizationContext, object> cst = (Tuple<SynchronizationContext, object>)state;
cst.Item1.Send(Writer, "Message");
}
public void Writer(object s)
{
Label1.Text = (s as string);
}
Take a look at the Async and Await stuff that’s now available in the runtime.
There’s a bit too much for me to create a sensible demo here, but I can point you at:
http://msdn.microsoft.com/en-gb/library/vstudio/hh191443.aspx
which should get you started.
Update
Here are a few more links that might help.
http://code.jonwagner.com/2012/09/06/best-practices-for-c-asyncawait/
http://www.itwriting.com/blog/4913-a-simple-example-of-async-and-await-in-c-5.html
http://weblogs.asp.net/dixin/archive/2012/11/02/understanding-c-async-await-1-compilation.aspx
Note: there is a lot of stuff around on the newer C#5 Async stuff, but if you look hard enough there is still a lot of the C#4 async stuff around too, it’s just that C#5 is in the limelight at the moment, so you might have to sift through things just that little bit further.