Search code examples
c#asynchronousdelegatescode-golf

Most Concise way to Invoke a void Method Asynchronously


I have a method which I would like to invoke asynchronously:

void Foo()
{
}

I can indeed invoke this asynchronously by the following:

delegate void DVoidMethod();
DVoidMethod FooDelegate = new DVoidMethod(Foo);
FooDelegate.BeginInvoke(null,null);

Has anyone got any alternatives?

I think three lines of code is too much?


Solution

  • Disclaimer:

    Don't use this in real code. This is just an attempt to shorten the code OP mentioned. To do real async calls without getting results back, use:

    ThreadPool.QueueUserWorkItem(stateObject => Foo());
    

    Use Action and Func delegates in the framework:

    new Action(Foo).BeginInvoke(null, null);
    

    Action<T> has been around since 2.0. Other variants are added in 3.5. On 2.0, you can, however, declare a bunch of them somewhere manually for further use; or even better, use LINQBridge.