I'm relatively new to C#, so please bear with me.
I am trying to understand how Task FromAsync works.
var task1 = Task<int>.Factory.FromAsync(Foo1, ...); //what happens here? Is this
called on a thread from threadpool?
SomeCode1(); // <- is this code executed in parallel with Foo1
task1.ContinueWith(Foo2,...); //does this block the current thread until Foo1
finishes? Shouldn't it act like a callback? If this whole code runs on a "normal"
thread does it block it? If this runs on a thread from a thread pool does it
release the thread until Foo1 finishes?
SomeCode2();
Thank you for your help, I'm really struggling with async programming.
FromAsync
provides a convenient mechanism which uses theBeginXxx
andEndXxx
methods of the Asynchronous Programming Model (APM) to create aTask
.The resulting
Task
will, by default, be executed on a thread pool thread (and your subsequent call toSomeCode1()
will indeed execute on the current thread, in parallel to theTask
).The
ContinueWith
method onTask
does indeed act rather like a callback, i.e. the delegate provided to this method will execute after the task has finished, also on some thread pool thread. It does not block the current thread.Indeed, you should set up this continuation when creating the task, e.g.
For more general and detailed info on threading in .NET I thoroughly recommend reading a good text such as part V of CLR via C#.