I'm trying to work on a proof of concept app, and I would like to know the internals of below two Async Methods.
Would Task.Result
cause any issues in DoSomethingAsync1()
?
I've read a bit about some blocking and deadlock issues that Task.Result
can cause, but I think it wouldn't in this case, since it runs on a separate task and there is an await
on the task which already ensures the Result.
The main goal here is to run the async method on a separate task, since this operation doesn't depend on main asp.net thread, and more importantly catch any exceptions thrown by DoSomethingThatTakesReallyLong()
Also,in the ActionResult
DoSomething()
, should I set .ConfigureAwait(false);
?
Are there any hidden bottlenecks/issues that I need to be aware of in the below scenario?
Update
I've fixed the typo I made when typing the question here. (returning user object instead of a task)
Also, I'm not at the liberty of converting all the higher level methods to async
at one go in the actual application. So, this is something I'm planning to do in a step-by-step way, starting with operations that doesn't depend on main thread.
I really appreciate all the best-practices answers as well, but this being a little playground code, my main question was to know if there are internal differences between DoSomethingAsync1()
and DoSomethingAsync2()
that might cause any issues under a certain condition.
From reading through the comments and answers, I get an idea that there isn't much difference.
private static async Task<User> DoSomethingAsync1()
{
try
{
var longRunningTask = Task<User>.Factory.StartNew(() => LongRunner.LongRunnerInstance.DoSomethingThatTakesReallyLong());
var user = await longRunningTask;
//Will the below line of code cause any issue?
Console.WriteLine(longRunningTask.Result.Id);
return user;
}
catch (Exception ex)
{
Console.WriteLine(ex);
return null;
}
}
private static async Task<User> DoSomethingAsync2()
{
try
{
var longRunningTask = Task<User>.Factory.StartNew(() => LongRunner.LongRunnerInstance.DoSomethingThatTakesReallyLong());
var user = await longRunningTask;
Console.WriteLine(user.Id);
return user;
}
catch (Exception ex)
{
Console.WriteLine(ex);
return null;
}
}
public ActionResult Index()
{
//Things that run on main Asp.NET thread
//Things that run independently
//Won't be using the task returned here at the moment.
DoSomethingAsync1();
//Do more things on main Asp.NET thread if needed
return View();
}
https://blog.stephencleary.com/2012/07/dont-block-on-async-code.html
https://msdn.microsoft.com/en-us/magazine/jj991977.aspx
Thanks