difference between task.run and async [duplicate] - c#

This question already has answers here:
Difference between passing a regular and async anonymous function to Task.Run for asynchronous work
(2 answers)
What is the difference between Task.Run() and await Task.Run()?
(2 answers)
Closed 3 years ago.
I'm having a bit of a sanity check that needs resolving:
Is there a difference between
Task.Run(async () => await dothingAsync());
and
Task.Run(dothingAsync);
Edit (signature of dothingasync)
private Task dothingAsync();
Or
private async Task dothingAsync();

Here's a blog post on the subject that dives into more detail. There's also this Stack Overflow post that is very similar except it deals with methods and your question deals with lambdas (which are converted by the compiler into methods).
In summary, the two approaches are almost equivalent. Using the keywords does introduce a state machine. In this case - since the lambda just calls a single method and returns its result - eliding the keywords is appropriate. If you do include async and await, it would just add a bit of overhead for no benefit.

Related

Why is the current thread changed when a Task awaits another Task? [duplicate]

This question already has answers here:
async/await different thread ID
(4 answers)
async - stay on the current thread?
(3 answers)
Is it needed to make fields thread-safe when using async/await?
(4 answers)
Do async and await produce acquire and release semantics?
(1 answer)
Closed last year.
Given the following code:
public static async Task TestTask()
{
Console.WriteLine(Thread.CurrentThread.ManagedThreadId);
await Task.Delay(1000);
Console.WriteLine(Thread.CurrentThread.ManagedThreadId);
}
We see that the current thread is changed after the await. However, this code is not multi-threaded and instead it is meant to provide non-blocking IO (with reference to JavaScript's mechanism). But why does it happen? and since it happens, does it mean that anything that comes after the awaited line must consider thread-safety (for example adding to a HashSet) while that would not be needed before that awaited line?

If awaiting an async method right away then why not just use a synchronous call? [duplicate]

This question already has answers here:
How and when to use ‘async’ and ‘await’
(25 answers)
How does await async work in C# [closed]
(2 answers)
Closed 4 years ago.
I'm getting the basics down with async/await in C# and can't think of any reasons why someone is calling an async method that returns Task which they immediately await.
Would this not be better just to run the method synchronously to reduce the overhead of running the async method?
Or could it be the case of the method signature already being set that is dictating how it is being called?

How to access the T object of a Task<T> [duplicate]

This question already has answers here:
Get result from async method
(2 answers)
Closed 5 years ago.
I am using an async method synchronously using the Task.Wait() method, but when the call is complete I would like to access to the object templated by the Task<>.
Task<HttpResponseMessage> message = _httpClient.GetAsync(Globals.ENDPOINT_URI + Uri.EscapeDataString(query));
message.Wait();
How do I access the HttpResponseMessage of the message object ?
Thank you
You'll want to use async/await, as it's considered a bad practice to use Wait and Result. Your code would be updated to the following:
HttpResponseMessage message =
await _httpClient.GetAsync(Globals.ENDPOINT_URI + Uri.EscapeDataString(query));
await will both wait for the call to complete and provide the result, which will sit in your message variable.
There are plenty of good resources on the Internet and great answers here on Stack Overflow regarding async/await, introduced in C# 5. Here's one page to get you started: https://learn.microsoft.com/en-us/dotnet/csharp/async.
EDIT: Here's a good resource on the Result problem: https://blog.stephencleary.com/2012/07/dont-block-on-async-code.html

Does it make sense to await a Task when there are no more operations after? [duplicate]

This question already has answers here:
Why use async and return await, when you can return Task<T> directly?
(9 answers)
Closed 5 years ago.
Let say that we have a method:
public async Task FlushBuffer(List<UmtsCellKpiReceived> kpis)
{
await _umtsCellService.ProcessUmtsCellKpi(kpis).ConfigureAwait(false);
}
Does it make sense to await this Task here? In one of the recent discussions I had, I learned that not awaiting creates an orphaned task which risks an UnobservedTaskException if MyTask() throws.
Is this a valid reason to await everything ?
In your case, just a single line method, you can just return the Task itself, no async/await required. The calling code is able to await the Task itself if it makes sense for it to do so.

Are async/await and return Task same? [duplicate]

This question already has answers here:
Any difference between "await Task.Run(); return;" and "return Task.Run()"? [duplicate]
(4 answers)
Closed 7 years ago.
There are two methods
public async Task T1()
{
await Task.Run(() => /*do something here*/);
}
public Task T2()
{
return Task.Run(() => /*do something here*/);
}
Is there any difference between them?
I believe the first variant will wait for the task to finish (not by blocking the thread, but by signing the rest of the method up to be executed when the task is done, in the Continuation Passing Style). The second option won't. You've started and returned a task, but your calling thread will just carry on unless it calls .Wait() or something.
The async/await stuff is just syntactic sugar around re-writing methods using Task and the continuation passing style, though the result is typically complex enough that you wouldn't do it by hand.

Categories