locked
Delegate.BeginInvoke and ThreadPool RRS feed

  • Question

  • Hi,

    I have been trying to an answer to this question, but so far no luck.

    Considering the new capabilities of the TPL in .NET 4, does delegate.BeginInvoke also use the same mechanism? If I have a bunch of .BeginInokes, then will work-stealing also apply to them? Will .BetingInvokes run on the same thread-pool as Tasks at all?

    Thanks.

    Saturday, January 29, 2011 8:50 AM

Answers

  • Delegate.BeginInvoke is also *significantly* slower than either Tasks or ThreadPool.QueueUserWorkItem. While it does schedule work to the ThreadPool (which Tasks also target by default), it goes through parts of the .NET Remoting stack to get there.  It's also not able to take advantage of the work-stealing queues added to the ThreadPool in .NET 4, whereas Tasks can.

    If you have a delegate SomeDelegate, and you're choosing between:

        SomeDelegate.BeginInvoke(iar =>
        {
            T result = SomeDelegate.EndInvoke(iar);
        }, null);

    and:

        Task<T> result = Task.Factory.StartNew(() => SomeDelegate());

    you should choose the latter.

    Sunday, January 30, 2011 12:03 AM
    Moderator

All replies

  • Delegate.BeginInvoke does run the delegate using a ThreadPool thread.  This will cause it to have the same runtime behavior as other ThreadPool threads on .NET 4.

     

    However, it doesn't have the ability and flexibility to schedule itself the same way as the new Tasks in TPL (ie: Custom schedulers, "AttachedToParent", etc).  It's more like using ThreadPool.QueueUserWorkItem to run the method.

     

    I would recommend using the TPL for background processing and scheduling in .NET 4 and above.  It provides many benefits once you learn it - from extra capabilities to ease of debugging (Parallel Tasks/Stacks windows are very nice when used with Tasks, especially Tasks that start other Tasks internally).

     

     


    Reed Copsey, Jr. - http://reedcopsey.com
    If a post answers your question, please click "Mark As Answer" on that post and "Mark as Helpful".
    Saturday, January 29, 2011 8:44 PM
    Moderator
  • Delegate.BeginInvoke is also *significantly* slower than either Tasks or ThreadPool.QueueUserWorkItem. While it does schedule work to the ThreadPool (which Tasks also target by default), it goes through parts of the .NET Remoting stack to get there.  It's also not able to take advantage of the work-stealing queues added to the ThreadPool in .NET 4, whereas Tasks can.

    If you have a delegate SomeDelegate, and you're choosing between:

        SomeDelegate.BeginInvoke(iar =>
        {
            T result = SomeDelegate.EndInvoke(iar);
        }, null);

    and:

        Task<T> result = Task.Factory.StartNew(() => SomeDelegate());

    you should choose the latter.

    Sunday, January 30, 2011 12:03 AM
    Moderator