Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/multithreading/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 自定义事件的线程上下文?_C#_Multithreading_Threadpool - Fatal编程技术网

C# 自定义事件的线程上下文?

C# 自定义事件的线程上下文?,c#,multithreading,threadpool,C#,Multithreading,Threadpool,我有一些这样的代码 MyClass Foo = new MyClass() Foo.OnSomeEvent += new SomeEvent(Foo_SomeEvent); ThreadPool.QueueUserWorkItem(Foo.MyMethod, SomeParams); 我的问题是,当启动OnSomeEvent并调用此方法Foo_SomeEvent时,它是在threadpool下的线程上下文中执行,还是在threadpool上查询项目的线程中执行?如果触发事件的是Foo.MyMe

我有一些这样的代码

MyClass Foo = new MyClass()
Foo.OnSomeEvent += new SomeEvent(Foo_SomeEvent);
ThreadPool.QueueUserWorkItem(Foo.MyMethod, SomeParams);

我的问题是,当启动OnSomeEvent并调用此方法Foo_SomeEvent时,它是在threadpool下的线程上下文中执行,还是在threadpool上查询项目的线程中执行?

如果触发事件的是
Foo.MyMethod
,由于
Foo.MyMethod
在池中的线程上运行,因此事件回调也将在池中的线程上运行。这很容易验证:

public class MyClass
{
    public EventHandler OnSomeEvent;
    public void MyMethod(object state)
    {
        OnSomeEvent(null, null);
    }
}

class Program
{
    static void Main()
    {
        Console.WriteLine(
            "main thread id: {0}", 
            Thread.CurrentThread.GetHashCode()
        );

        MyClass Foo = new MyClass();
        Foo.OnSomeEvent += new EventHandler(Foo_SomeEvent);
        ThreadPool.QueueUserWorkItem(Foo.MyMethod, null);
        Console.ReadKey();
    }

    static void Foo_SomeEvent(object sender, EventArgs e) 
    {
        Console.WriteLine(
            "Foo_SomeEvent thread id: {0}", 
            Thread.CurrentThread.GetHashCode()
        );
    }
}
在我的控制台上打印:

main thread id: 1
Foo_SomeEvent thread id: 3

如果触发事件的是
Foo.MyMethod
,因为
Foo.MyMethod
在池中的线程上运行,那么事件回调也将在池中的线程上运行。这很容易验证:

public class MyClass
{
    public EventHandler OnSomeEvent;
    public void MyMethod(object state)
    {
        OnSomeEvent(null, null);
    }
}

class Program
{
    static void Main()
    {
        Console.WriteLine(
            "main thread id: {0}", 
            Thread.CurrentThread.GetHashCode()
        );

        MyClass Foo = new MyClass();
        Foo.OnSomeEvent += new EventHandler(Foo_SomeEvent);
        ThreadPool.QueueUserWorkItem(Foo.MyMethod, null);
        Console.ReadKey();
    }

    static void Foo_SomeEvent(object sender, EventArgs e) 
    {
        Console.WriteLine(
            "Foo_SomeEvent thread id: {0}", 
            Thread.CurrentThread.GetHashCode()
        );
    }
}
在我的控制台上打印:

main thread id: 1
Foo_SomeEvent thread id: 3

很好的例子证明了这一点。感谢一个例子来证明这一点。谢谢