views:

58

answers:

3

I know that Asycronous Delegates are used for implementing Call back functionality in .NET.

I want to know

  1. Is it possible to use Callback using ThreadPool?
  2. Can I use as many BackgroundWorkers as possible? What I exactly want to know is, Is there any additional overhead involved in using BackgroundWorker instead of ThreadPool/AsyncDelegates/Thread Class?
A: 

BackgroundWorker is implemented using delegate invoked asynchronously. Target method of delegate invoked asynchronously is executed on a thread from the thread pool.

Dzmitry Huba
+1  A: 

In response to your first question (if I understood correctly), the answer is yes: I think you are looking for the AsyncOperation class, which can handle reporting progress and completed events back to the calling thread using its Post and PostOperationCompleted methods. This is what the BackgroundWorker is doing under the hood.

See: AsyncOperation Class

private AsyncOperation asyncOperation;

public void DoSomethingAsync()
{
    this.asyncOperation = AsyncOperationManager.CreateOperation(null);
    ThreadPool.QueueUserWorkItem(s => this.DoSomethingImpl());
}

private void DoSomethingImpl()
{
    // report progress
    this.asyncOperation.Post(new SendOrPostCallback(...), null);

    // report complete
    this.asyncOperation.PostOperationCompleted(new SendOrPostCallback(...), null);
}
Dave
+1  A: 

Callbacks are already made on a thread pool thread, it is the default for .NET. Making one on a Thread you created yourself would be awkward. The worker thread for a BackgroundWorker also comes from the thread pool.

There is no fundamental upper limit on the number of BGWs you can use beyond available Windows resources. The thread pool manager is however not going to let them all run at the same time, it tries to make sure there are never as many active threads as there are cores in your CPU. Only when a thread doesn't complete in a reasonable amount of time does it allow more threads to run, up to the limit set by ThreadPool.SetMaxThreads(). The odds that you'll shoot your foot somehow goes up roughly quadratically with the number of threads you created.

Hans Passant