I have an asynchronous method in which I wish to invoke the SendAsync method as a fire-and-forget service. Consider the following code:
public async Task HandleAsync(DoStuffCommand command)
{
/*
* Performing various tasks..
*/
_client.SendAsync(myObject);
}
public async Task SendAsync(MyObject myObject)
{
/*
* Time consuming tasks..
*/
try
{
await call_1();
Trace.TraceInformation("Call1");
await call_2();
Trace.TraceInformation("Call2");
}
catch (Exception e)
{
Trace.TraceError(e.Message);
throw;
}
}
My problem is that for some reason call_2 is inconsistently getting called (very rarely). My suspicion is that the SendAsync method is not allowed to complete because the calling method HandleAsync does not await SendAsync and when the HandleAsync thread is terminated, the work in progress in SendAsync is too.
But, this is contrary to my understanding of async/await. I was under the impression that the SendAsync implementation would perform its work on a different thread in this scenario, and thus, be able to complete even if HandleAsync would return before SendAsync.
Maybe someone more async/await than myself can shed some light? Thank you.
UPDATE
I also tried adding a try/catch and traces. No exceptions are thrown but the trace consistently follows the behavior of the method calls, i.e. When both calls are made, so are both TraceInformation and when only call_1 is invoked, only the first TraceInformation runs.
I have an asynchronous method in which I wish to invoke the SendAsync method as a fire-and-forget service.
As I describe on my blog, fire-and-forget on ASP.NET is inherently dangerous and almost always the wrong solution to whatever requirement you're trying to meet. One of the main problems with "fire and forget" is that the background work is forgotten. There will always be some situations (hopefully rare) where the background work does not run, or is silently dropped. The only way to prevent this loss of work is to implement a reliable distributed system architecture.
My suspicion is that the SendAsync method is not allowed to complete because the calling method HandleAsync does not await SendAsync and when the HandleAsync thread is terminated, the work in progress in SendAsync is too.
ASP.NET is less about threads than it is about request contexts. When HandleAsync completes, the request context for that request is disposed, and that may cause some code in SendAsync to fail or behave erratically.
I was under the impression that the SendAsync implementation would perform its work on a different thread in this scenario, and thus, be able to complete even if HandleAsync would return before SendAsync.
No, absolutely not. async does not mean "run on another thread". If you want to run on another thread, then you have to do so explicitly (e.g., Task.Run). However, this is almost always a bad idea on ASP.NET.
If you want to minimize the loss of work, then use HostingEnvironment.QueueBackgroundWorkItem; if you want to prevent the loss of work, then either reject the fire-and-forget requirement or implement a proper distributed architecture. A proper distributed architecture is one with a reliable message queue (such as Azure Queues or MSMQ) with an independent worker process (such as Azure Functions or Win32 Services).
Related
In a blog post, Microsoft's Sergey Tepliakov says:
you should always provide
TaskCreationOptions.RunContinuationsAsynchronously when creating
TaskCompletionSource instances.
But in that article, unless I misunderstood it, he also says that all await continuations basically act the same way as a TaskCompletionSource without TaskCreationOptions.RunContinuationsAsynchronously. So this would mean that async and await are also inherently dangerous and shouldn't be used, unless await Task.Yield() is used as well.
(edit: I did misunderstand it. He's saying that await continuing synchronously is the cause of the problematic SetResult behaviour. await Task.Yield() is recommended as a client-side workaround if the task creation can't be controlled at the source. Unless I misunderstood something again.)
I conclude that there must be specific circumstances that make synchronous continuations dangerous, and apparently that those circumstances are common for TaskCompletionSource use cases. What are those dangerous circumstances?
Thread theft, basically.
A good example here would be a client library that talks over the network to some server that is implemented as a sequence of frames on the same connection (http/2, for example, or RESP). For whatever reason, imagine that each call to the library returns a Task<T> (for some <T>) that has been provided by a TaskCompletionSource<T> that is awaiting results from the network server.
Now you want to write the read-loop that is dequeing responses from the server (presumably from a socket, stream, or pipeline API), resolve the corresponding TaskCompletionSource<T> (which could mean "the next in the queue", or could mean "use a unique correlation key/token that is present in the response").
So you effectively have:
while (communicationIsAlive)
{
var result = await ParseNextResultAsync(); // next message from the server
TaskCompletionSource<Foo> tcs = TryResolveCorrespondingPendingRequest(result);
tcs?.TrySetResult(result); // or possibly TrySetException, etc
}
Now; imagine that you didn't use RunContinuationsAsynchronously when you created the TaskCompletionSource<T>. The moment you do TrySetResult, the continuation executes on the current thread. This means that the await in some arbitrary client code (which can do anything) has now interrupted your IO read loop, and no other results will be processed until that thread relinquishes the thread.
Using RunContinuationsAsynchronously allows you to use TrySetResult (et al) without worrying about your thread being stolen.
(even worse: if you combine this with a subsequent sync-over-async call to the same resource, you can cause a hard deadlock)
Related question from before this flag existed: How can I prevent synchronous continuations on a Task?.
If you have an async function:
public async Task DoWork()
{
await DoSomeWorkAsync();
await DoSomeMoreWorkAsync();
}
Now the first await prevents the method blocking the calling context, so is useful.
But after DoSomeWorkAsync has completed, the method is anyways running in a different context, since in the compiler its been converted to something like Task.ContinueWith(await DoSomeMoreWorkAsync()).
So is their any purpose to awaiting DoSomeMoreWorkAsync/running it async? Are there any disadvantages? Should I use a non-async version of DoSomeMoreWorkAsync if it exists?
ie. would this be disadvantageous in any way:
public async Task DoWork()
{
await DoSomeWorkAsync();
DoSomeMoreWork();
}
EDIT: This is not the same question as Multiple Awaits in a single method. That asks what happens. I'm asking is there any advantage to that happening.
It seems you are thinking that avoiding blocking of the caller is the only purpose of async methods, that's not so. Async methods are usually async because at some point they perform asynchronous IO, such as working with files, databases, web requests and so on (or calling other async methods that do this).
When real async IO is in progress, no thread in your application is busy waiting for it to complete (well, there is thread, but it's one for the whole application, not per specific IO task).
That means even IF await DoSomeMoreWorkAsync executes on some thread pool thread - when at some point it will reach async IO - this thread pool thread will be released and will be available for more useful work.
On the other hand, if you will use synchronous version instead (DoSomeMoreWork) - it will block current thread pool thread for the whole duration, including IO, so this thread will not be available for useful work.
Releasing threads whenever possible might be quite important in applications using them heavily, such as web applications.
In addition to the above, this statement
But after DoSomeWorkAsync has completed, the method is anyways running
in a different context
is not always true. For example in UI application, if you call DoWork from UI thread, continuation (await DoSomeMoreWorkAsync()) will also be executed on UI thread. That means if you replace it with synchronous version - UI thread will freeze for the duration of it.
So is there any purpose to awaiting DoSomeMoreWorkAsync?
Well, if it is asynchronous, then you absolutely want to await it so your DoWork method does not complete before that “some more work” is also done. If it was asynchronous, and you did not await it, it would essentially be fire and forget which is very rarely what you want.
So is there any purpose to running it async?
That depends on the function. You do not make methods asynchronous because you want to call them asynchronous. Methods are asynchronous because they perform asynchronous tasks.
If the method is doing purely CPU bound work which won’t run asynchronous anyway, then there is no reason in making it asynchronous, no. Actually, leave it synchronous to clearly communicate to the callers that there is no asynchronous process going on.
But if it is something that benefits from being asynchronous, e.g. because it does asynchronous network or I/O calls, then it probably should be asynchronous. And then you should also await it.
Are there any disadvantages?
There are always disadvantages. Running asynchronous code is more expensive than running synchronous code because there is a non-trivial amount of overhead being generated and called (which we luckily don’t have to deal with when writing async code). But that overhead does not really matter when looking at the advantages real asynchronous code can give you.
So you really shouldn’t use this to decide whether to make something asynchronous or not. Think about what the method does and how it does it, and then decide whether that process is synchronous or asynchronous.
I need to call an async method from MeasureOverride. This call should be synchronous because I need to return the value of the async method.
I tried about a dozen different calls from these threads:
Synchronously waiting for an async operation, and why does Wait() freeze the program here
How would I run an async Task<T> method synchronously?
They all failed, some wouldn't compile in Universal Windows Applications, some weren't synchronous, some provoked a deadlock etc..
I feel strongly against async/await because of how it contaminates the call hierarchy prototypes. At the override level I'm stuck with no async keyword and I need to call await synchronously from the blackbox. Concretely how should I go about it?
The first thing you should do is take a step back. There should be no need to call asynchronous code from within a MeasureOverride in the first place.
Asynchronous code generally implies I/O-bound operations. And a XAML UI element that needs to send a request to a remote web server, query a database, or read a file, just to know what its size is, is doing it wrong. That's a fast track to app certification rejection.
The best solution is almost certainly to move the asynchronous code out of the element itself. Only create/modify the UI elements after the necessary asynchronous work completes.
That said, if you feel you must block the UI thread while asynchronous operations complete, I've compiled a list of every hack I know of, published in my MSDN article on brownfield asynchronous development.
Lets say you have a service API call. The callee is somewhat performance critical, so in order not to hold up the API call any longer than necessary, there's an SaveAsync() method that is used. I can't await it, however, because that would hold up the API call just as long (or perhaps even longer) than the non-async version.
The reason I'm asking is this: If you don't await the call, is there a chance the Task object returned gets garbage collected? And if so, would that interrupt the running task?
The reason I'm asking is this: If you don't await the call, is there a chance the Task object returned gets garbage collected?
Generally, no, that shouldn't happen. The underlying TaskScheduler which queues the task, usually keeps a reference to it for the desired life-time until it completes. You can see that in the documentation of TaskScheduler.QueueTask:
A typical implementation would store the task in an internal data structure, which would be serviced by threads that would execute those tasks at some time in the future.
Your real problem is going to be with the ASP.NET SynchronizationContext, which keeps track of any on-going asynchronous operation at runtime. If your controller action finishes prior to the async operation, you're going to get an exception.
If you want to have "fire and forget" operations in ASP.NET, you should make sure to register them with the ASP.NET runtime, either via HostingEnvironment.QueueBackgroundWorkItem or BackgroundTaskManager
No, it won't interrupt the running task, but you won't observe the exceptions from the task either, which is not exactly good. You can (at least partially) avoid that by wrapping all running code in a try ... catch and log the exception.
Also, if you're inside asp.net, then your whole application could be stopped or recycled, and in this case your task will be interrupted. This is harder to avoid - you can register for AppPool shutdown notification, or use something like Hangfire.
Probably this question has already been made, but I never found a definitive answer. Let's say that I have a Web API 2.0 Application hosted on IIS. I think I understand that best practice (to prevent deadlocks on client) is always use async methods from the GUI event to the HttpClient calls. And this is good and it works. But what is the best practice in case I had client application that does not have a GUI (e.g. Window Service, Console Application) but only synchronous methods from which to make the call? In this case, I use the following logic:
void MySyncMethodOnMyWindowServiceApp()
{
list = GetDataAsync().Result().ToObject<List<MyClass>>();
}
async Task<Jarray> GetDataAsync()
{
list = await Client.GetAsync(<...>).ConfigureAwait(false);
return await response.Content.ReadAsAsync<JArray>().ConfigureAwait(false);
}
But unfortunately this can still cause deadlocks on client that occur at random times on random machines.
The client app stops at this point and never returns:
list = await Client.GetAsync(<...>).ConfigureAwait(false);
If it's something that can be run in the background and isn't forced to be synchronous, try wrapping the code (that calls the async method) in a Task.Run(). I'm not sure that'll solve a "deadlock" problem (if it's something out of sync, that's another issue), but if you want to benefit from async/await, if you don't have async all the way down, I'm not sure there's a benefit unless you run it in a background thread. I had a case where adding Task.Run() in a few places (in my case, from an MVC controller which I changed to be async) and calling async methods not only improved performance slightly, but it improved reliability (not sure that it was a "deadlock" but seemed like something similar) under heavier load.
You will find that using Task.Run() is regarded by some as a bad way to do it, but I really couldn't see a better way to do it in my situation, and it really did seem to be an improvement. Perhaps this is one of those things where there's the ideal way to do it vs. the way to make it work in the imperfect situation that you're in. :-)
[Updated due to requests for code]
So, as someone else posted, you should do "async all the way down". In my case, my data wasn't async, but my UI was. So, I went async down as far as I could, then I wrapped my data calls with Task.Run in such as way that it made sense. That's the trick, I think, to figure out if it makes sense that things can run in parallel, otherwise, you're just being synchronous (if you use async and immediately resolve it, forcing it to wait for the answer). I had a number of reads that I could perform in parallel.
In the above example, I think you have to async up as far as makes sense, and then at some point, determine where you can spin off a t hread and perform the operation independent of the other code. Let's say you have an operation that saves data, but you don't really need to wait for a response -- you're saving it and you're done. The only thing you might have to watch out for is not to close the program without waiting for that thread/task to finish. Where it makes sense in your code is up to you.
Syntax is pretty easy. I took existing code, changed the controller to an async returning a Task of my class that was formerly being returned.
var myTask = Task.Run(() =>
{
//...some code that can run independently.... In my case, loading data
});
// ...other code that can run at the same time as the above....
await Task.WhenAll(myTask, otherTask);
//..or...
await myTask;
//At this point, the result is available from the task
myDataValue = myTask.Result;
See MSDN for probably better examples:
https://msdn.microsoft.com/en-us/library/hh195051(v=vs.110).aspx
[Update 2, more relevant for the original question]
Let's say that your data read is an async method.
private async Task<MyClass> Read()
You can call it, save the task, and await on it when ready:
var runTask = Read();
//... do other code that can run in parallel
await runTask;
So, for this purpose, calling async code, which is what the original poster is requesting, I don't think you need Task.Run(), although I don't think you can use "await" unless you're an async method -- you'll need an alternate syntax for Wait.
The trick is that without having some code to run in parallel, there's little point in it, so thinking about multi-threading is still the point.
Using Task<T>.Result is the equivalent of Wait which will perform a synchronous block on the thread. Having async methods on the WebApi and then having all the callers synchronously blocking them effectively makes the WebApi method synchronous. Under load you will deadlock if the number of simultaneous Waits exceeds the server/app thread pool.
So remember the rule of thumb "async all the way down". You want the long running task (getting a collection of List) to be async. If the calling method must be sync you want to make that conversion from async to sync (using either Result or Wait) as close to the "ground" as possible. Keep they long running process async and have the sync portion as short as possible. That will greatly reduce the length of time that threads are blocked.
So for example you can do something like this.
void MySyncMethodOnMyWindowServiceApp()
{
List<MyClass> myClasses = GetMyClassCollectionAsync().Result;
}
Task<List<MyClass>> GetMyListCollectionAsync()
{
var data = await GetDataAsync(); // <- long running call to remote WebApi?
return data.ToObject<List<MyClass>>();
}
The key part is the long running task remains async and not blocked because await is used.
Also don't confuse the responsiveness with scalability. Both are valid reasons for async. Yes responsiveness is a reason for using async (to avoid blocking on the UI thread). You are correct this wouldn't apply to a back end service however this isn't why async is used on a WebApi. The WebApi is also a non GUI back end process. If the only advantage of async code was responsiveness of the UI layer then WebApi would be sync code from start to finish. The other reason for using async is scalability (avoiding deadlocks) and this is the reason why WebApi calls are plumbed async. Keeping the long running processes async helps IIS make more efficient use of a limited number of threads. By default there are only 12 worker threads per core. This can be raised but that isn't a magic bullet either as threads are relatively expensive (about 1MB overhead per thread). await allows you to do more with less. More concurrent long running processes on less threads before a deadlock occurs.
The problem you are having with deadlocks must stem from something else. Your use of ConfigureAwait(false) prevents deadlocks here. Solve the bug and you are fine.
See Should we switch to use async I/O by default? to which the answer is "no". You should decide on a case by case basis and choose async when the benefits outweigh the costs. It is important to understand that async IO has a productivity cost associated with it. In non-GUI scenarios only a few targeted scenarios derive any benefit at all from async IO. The benefits can be enormous, though, but only in those cases.
Here's another helpful post: https://stackoverflow.com/a/25087273/122718