Reputation: 351
I want to return an action using Async and await functionality in dot net 4.5. I have used the following code.
public async Task<ActionResult> DisplayDashboard()
{
await Task.Run(() =>
{
if (true)
{
return RedirectToAction("Index", "Home");
}
else
{
return RedirectToAction("Error", "Home");
}
});
}
Its giving following error, "Cannot convert lambda expression to delegate type 'System.Action' because some of the return types in the block are not implicitly convertible to the delegate return type".
Can anybody please suggest me how to perform RedirectToAction using Task.
Upvotes: 8
Views: 13079
Reputation: 11
This is old but is the first result returned from Google so worth correcting. The return from RedirectToAction() or View() cannot be continued so why await the results. Therefore there is no need to artificially Task.Run() only to await it. The async keyword will already lift any returns into a Task. The resulting code is cleaner.
public async Task<ActionResult> DisplayDashboard()
{
if (true)
{
return RedirectToAction("Index", "Home");
}
else
{
return View("Error");
}
}
Upvotes: 0
Reputation: 1354
Why do you need this code async? If all you need is to make this method return a Task to satisfy some interface requirement, then use:
public Task<ActionResult> DisplayDashboard()
{
ActionResult result;
if (true)
{
result = RedirectToAction("Index", "Home");
}
else
{
result = View("Index");
}
return Task.FromResult(result);
}
Task.Run() would actually use a different thread to the code you pass into it. It doesn't seem that you need to do that here.
Upvotes: 4
Reputation: 2460
public async Task<ActionResult> DisplayDashboard()
{
return await Task.Run<ActionResult>(() =>
{
if (true)
{
return RedirectToAction("Index", "Home");
}
else
{
return View("Index");
}
});
}
Upvotes: 13