Jan Deinhard
Jan Deinhard

Reputation: 20205

Is there a way to determine the thread in which the handler is executed when using BeginInvoke?

I want to determine the thread in which the handler is executed when using BeginInvoke. Right now each time I invoke the method the handler gets executed by a different thread. Is there a way to determine the thread?

using System;
using System.Threading;
using System.Runtime.Remoting.Messaging;

namespace Delegate
{
  public delegate void BarDelegate(string argument);

  public class Foo
  {
    private void handleBar(string argument)
    {
      int threadId = AppDomain.GetCurrentThreadId();
      Console.WriteLine("Argument is " + argument + " " + threadId.ToString());
    }

    public void bar(string argument)
    {
      BarDelegate smd = new BarDelegate(this.handleBar);
      smd.BeginInvoke(argument, null, null);
    }

    public static void Main()
    {
      Console.WriteLine(AppDomain.GetCurrentThreadId().ToString());
      Foo ds = new Foo();
      ds.bar("Hello, world!");
      Console.ReadLine();
      ds.bar("Hello, world!");
      Console.ReadLine();
    }
  }
}

Upvotes: 2

Views: 158

Answers (3)

Hans Passant
Hans Passant

Reputation: 942338

Getting asynchronous code to execute on a specific thread requires a synchronization provider. There are two main ones in the .NET framework, WindowsFormsSynchronizationContext which helps Control.BeginInvoke() to run code on the UI thread. And DispatcherSynchronizationContext, supporting Dispatcher.BeginInvoke() for WPF. These providers are automatically installed when you call Application.Run() for these class libraries. They can only invoke to the UI thread.

There is no sync provider for a console mode program. And a delegate's BeginInvoke() method always executes on a threadpool thread. If you cannot use these class libraries and the component you use has no support for multi-threading (very few do, unless it is a COM server) then using threading is not an option available to you.

Upvotes: 4

Dagang Wei
Dagang Wei

Reputation: 26548

I think what you really want is having control of in which thread the async task is running. You can't use BeginInvoke, because it makes the task run in a random thread from the .NET ThreadPool. So, you need to create a thread first, then post task to it, in this way you have control. If you don't want to write your own, I recommend you use the SmartThreadPool, just google it.

Upvotes: 0

Aliostad
Aliostad

Reputation: 81700

This is because BeginInvoke uses the famous AppDomain's ThreadPool.

If you need to know which thread executes it - and you really really need to - then perhaps you need to create you own threads. ThreadPool (and for that matter BeginInvoke) is when we need something to be done and not caring how and when.

Upvotes: 2

Related Questions