Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

The correct way to Fire-and-Forget an asynchronous delegate

Consider me rusty on the subject of asynchronous delegates.

If I want to call a method asynchronously, in a fire-and-forget style, is this an appropriate way to do it?

Action action = DoSomething;
action.BeginInvoke(action.EndInvoke, null);

The DoSomething() method catches all exceptions and deals with them internally.

Is the call to EndInvoke appropriate? Required?

Is there a clearer way to achieve the same behaviour?

like image 369
Paul Turner Avatar asked Apr 13 '10 14:04

Paul Turner


2 Answers

The new way (in .NET 4) is to do this:

Task.Factory.StartNew(() => DoSomething());
like image 86
Andrew Hare Avatar answered Oct 05 '22 20:10

Andrew Hare


The "old-school" way in .NET 3.5 is to use the ThreadPool:

ThreadPool.QueueUserWorkItem(s => DoSomething());

If you prefer to use asynchronous delegates, then you should know that the call to EndInvoke is necessary, even if you don't have any additional code you wish to execute on callback.

like image 24
Aaronaught Avatar answered Oct 05 '22 20:10

Aaronaught