Often in application development you want a process to call another thread and continue the process flow, without waiting for a response from the called thread. This pattern is called the “fire and forget” pattern.
I myself are oblivious to async coding, but these methods have proven to be functioning in very large scale systems.
THE OLD WAY: USING THREADPOOL
The System.Threading.ThreadPool method have been around since .NET 1.0. The threadpool is a pool of threads that are available for you to use. The QueueUserWorkItem puts the method into a queue and executes the method when there is an available thread.
Please note that when the async method is called, the parameter is converted into an object, and you need to cast it back to the strong type before you can work with it:
using System; using System.Threading; using System.Threading.Tasks; namespace MyNamespace { public class MessageData { public string UserName { get; set; } public string IpAddress { get; set; } public string UserAgent { get; set; } } public class MyService { public static void DoWork(MessageData messageData) { ThreadPool.QueueUserWorkItem(new MyService().DoWorkAsync, messageData); } private void DoWorkAsync(object context) { try { MessageData messageData = (MessageData)context; // Do stuff with the messageData object } catch (Exception ex) { // Remember that the Async code needs to handle its own // exceptions, as the "DoWork" method will never fail } } } }
THE NEW WAY: TASK.FACTORY.STARTNEW
The Task class was introduced in .NET 4.something and is part of the new async/await keywords that makes async coding easier. The Task.Factory.StartNew() basically does the same as the TreadPool.QueueUserWorkItem but works with strong types:
using System; using System.Threading; using System.Threading.Tasks; namespace MyNamespace { public class MessageData { public string UserName { get; set; } public string IpAddress { get; set; } public string UserAgent { get; set; } } public class MyService { public static void DoWork(MessageData messageData) { Task.Factory.StartNew(() => DoWorkAsync(messageData)); } private void DoWorkAsync(MessageData messageData) { try { // Do stuff with the messageData object } catch (Exception ex) { // Remember that the Async code needs to handle its own // exceptions, as the "DoWork" method will never fail } } } }
MORE TO READ:
- Starting a fire and forget async method from StackExchange
- Using C# HttpClient from Sync and Async code by briancaos
- Fire-and-Forget Pattern from Enterprise Integration Patterns
Pingback: Because this call is not awaited, execution of the current method continues before the call is completed. Consider applying the ‘await’ operator to the result of the call | Brian Pedersen's Sitecore and .NET Blog
Pingback: Modelo de actores con Akka.Net – Mind Body And Code