You're probably looking for:
Task<bool> GetTrue()
{
return Task.FromResult(true);
}
instead of:
Task<bool> GetTrue()
{
return new Task<bool>(() => true);
}
In the latter case, you don't even start the task you create. You'd need to start it with Task.Run
or Task.RunSynchronously
. Usually you don't create tasks directly via new Task()
. Check Stephen Toub's "Task.Factory.StartNew" vs "new Task(...).Start" and "Task.Run vs Task.Factory.StartNew".
Depending on what you're trying to achieve, you might be tempted to do this:
Task<bool> GetTrue()
{
return Task.Run(() => true);
}
However, usually this turns to be a known-anti-pattern, check "Should I expose asynchronous wrappers for synchronous methods?".
Updated to address the comments:
... the context is a WCF service. The Task.Factory.FromAsync() call is wrapping the Begin...() and End...() functions that the service has pushed to the consumer. But I see no way to actually start the task and it just hangs. ... it is the client-side making the WCF call. The client-side app is a Windows Phone 8 application.
You're experiencing a deadlock on the UI thread, because you're blocking on the result of a pending task (with task.Result
). The task itself cannot be completed, because the await
continuation is posted asynchronously to the dispatcher loop of the UI thread of your WP8 app, which is now blocked. Stephen Cleary explains this in great details in his blog. To avoid this, you should embrace "async all the way down" programming model. It practically means that you should make your UI event and command handlers async
as well, and do var result = await task
, rather than var result = task.Result
in there.