Reputation: 1511
I have an issue with this simple async code. The execution goes througth the TestAsync action and goes througth the delay method but when the delay method returns nothing else happens. it seems like blocked for some reason.
public async Task<ActionResult> TestAsync()
{
try
{
var res = await doLongOperation();
return RedirectToAction("Index");
}
catch (Exception e) { }
}
private Task<bool> doLongOperation()
{
var test = new Task<bool>(() => { /*do the long operation..*/ return true; });
return test;
}
Any suggestion?
Upvotes: 0
Views: 428
Reputation: 1332
The method posted in your question doesn't work properly because the task is not started, there's nothing finishing so your await is waiting indefinitely. If you want to use Async it's best to use async all the way down, especially in an ASP.NET context. If you are not doing anything that is truly asynchronous, then in a web development context, just allow it to be synchronous.
I honestly believe the most good that will be done here is for you to spend time studying async/await, an excellent resource is found here: Stephen Cleary Blog on Async
Upvotes: 0
Reputation: 27871
new Task<bool>(() => true)
returns a task that is not started yet. This is an old syntax that requires you to invoke the Start
method on the task. If you don't invoke the Start
method, the task will never complete, and thus asynchronous execution will never continue (await
will asynchronously wait forever).
If you simply want to delay execution, then simply use Task.Delay
like this:
private async Task<bool> delay()
{
await Task.Delay(1000);
return true;
}
In general, it is always recommended to create tasks that are already started upon creation.
If you want to create a task that runs on a thread-pool thread, then use the Task.Run
method.
Upvotes: 1