Reputation: 29421
Let's say you have this console application:
static void Main(string[] args)
{
var httpClient = new HttpClient()
{ BaseAddress = new Uri("http://www.timesofmalta.com") };
var responseTask = httpClient.GetAsync("/");
}
Since the task is not awaited, the program reaches its end, finds no other foreground threads executing, and exits before any response is received. That's pretty clear because this is a console application.
Now let's say you have a WCF application, where a request similarly causes a task to be spawned, but does not await it. Let's say this task is long-running, and is fire-and-forget rather than anything like an HTTP GET.
In such a case, what happens to that task? Does the thread just die as in the console application, bringing down the task with it? Can this cause code occurring later in the task to not be executed?
Upvotes: 4
Views: 170
Reputation: 456507
It depends on how your WCF is hosted. Whenever the application exits, its threads will be torn down, and any outstanding asynchronous operations are simply dropped.
Note that if WCF is hosted in ASP.NET, then fire-and-forget is dangerous; ASP.NET will recycle your app periodically just to keep things clean, and at that time your fire-and-forget operation can disappear. ASP.NET provides APIs to register work like this (if you absolutely must do it in-process).
If you're running on another host, you'll have to take care of registering with that host, using whatever technique is available.
Or, you can introduce a proper distributed architecture: the WCF endpoint merely serializes a description of the work to be done into a reliable queue (Azure queue / MSMQ / WebSphereMQ / etc), and an independent background worker processes that work (Azure webjob / Azure worker role / Win32 service / etc). This is a more complex setup but fixes the "lost work" problem you can get if you try to have your WCF app do it all in-process.
Upvotes: 3