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
Related
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?
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.
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?
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.
This question already has answers here:
C# asynchronous method - help needed
(3 answers)
Closed 8 years ago.
I have the following code that I'm using to call a uri:
var uri = string.Format("Helpers/ProfileList/Online/?locationId=0&skip=0&take={0}", numProfiles);
HttpResponseMessage response = await client.GetAsync(uri);
response.EnsureSuccessStatusCode();
The uri is pointing at a custom web api uri (which I can debug and follow through). However, when the last return statement in the api has been called, nothing seems to happen. It should go to the response.EnsureSuccessStatusCode(); line, but it's not. It just seems to be hanging.
My spidey-sense tells me that further up your call stack your code is blocking on a returned task, e.g., Task.Wait or Task<T>.Result. By default, this will cause a deadlock that I explain on my blog.
To fix it, replace Task.Wait and Task<T>.Result with await.