Simplest way to do a fire and forget method in C#?
To add to Will's answer, if this is a console application, just throw in an AutoResetEvent
and a WaitHandle
to prevent it exiting before the worker thread completes:
Using System;
Using System.Threading;
class Foo
{
static AutoResetEvent autoEvent = new AutoResetEvent(false);
static void Main()
{
ThreadPoolQueueUserWorkItem(new WaitCallback(FireAway), autoEvent);
autoEvent.WaitOne(); // Will wait for thread to complete
}
static void FireAway(object stateInfo)
{
System.Threading.Thread.Sleep(5000);
Console.WriteLine("5 seconds later");
((AutoResetEvent)stateInfo).Set();
}
}
ThreadPool.QueueUserWorkItem(o => FireAway());
(five years later...)
Task.Run(() => FireAway());
as pointed out by luisperezphd.
For C# 4.0 and newer, it strikes me that the best answer is now given here by Ade Miller: Simplest way to do a fire and forget method in c# 4.0
Task.Factory.StartNew(() => FireAway());
Or even...
Task.Factory.StartNew(FireAway);
Or...
new Task(FireAway).Start();
Where
FireAway
ispublic static void FireAway() { // Blah... }
So by virtue of class and method name terseness this beats the threadpool version by between six and nineteen characters depending on the one you choose :)
ThreadPool.QueueUserWorkItem(o => FireAway());
For .NET 4.5:
Task.Run(() => FireAway());