带线程的事件处理

本文关键字:事件处理 线程 | 更新日期: 2023-09-27 18:20:41

总体情况是让Thread t1打印到某个值,然后根据另一个线程s执行的signal (ManualResetEvent)暂停执行。在s完成之后,它是sets the signal。因此,T恢复执行。

class A
{
    int key;
    int temp;
    public A(int x)
    {
        key = x;
    }
    public EventHandler eventHandler;
    private void onKeyReached(object sender, EventArgs e)
    {
        eventHandler(this, e);
    }
    public int Temp
    {
        get { return temp; }
        set
        {
            if (value == temp) return;
            else if (temp == key)
                onKeyReached(this, EventArgs.Empty);
            else
                temp = value;
        }
    }
}
class Test
{
    static A a = new A(500);
    //signal to pause or resume threads
    static ManualResetEvent signal = new ManualResetEvent(true);
    static void Main()
    {
        a.eventHandler += WorkOnKeyReached;
        Thread t = new Thread(F);
        t.Start();
    }
    static void F()
    {
        for (int i = 0; i < 1000; i++)
        {
            a.Temp = i;
            //when a.Temp == a.Key, a.OnkeyReached() is fired.
            signal.WaitOne();
            Console.WriteLine(a.Temp);
        }
    }
    static void WorkOnKeyReached(object sender, EventArgs e)
    {
        signal.Reset();
        Thread s = new Thread(() =>
        {
            Console.WriteLine("Doing something else...");
            Thread.Sleep(3000);
            Console.WriteLine("Done..");
            signal.Set();
        });
        s.Start();
    }
}

程序在前半部分按预期工作,直到线程tsignal成为WorkOnKeyReached中的reset时暂停。然而,在WorkOnKeyReached完成之后,setsignal期望t继续。

输出:

1
2
..
500
Doing something else...
Done.
500
Doing something else...
Done.

有人能解释这种现象吗?我只是在玩线程和其他东西。

带线程的事件处理

    public int Temp
{
    get { return temp; }
    set
    {
        if (value == temp) return;
        else if (temp == key)
            onKeyReached(this, EventArgs.Empty);
       //else
            temp = value;
    }
}

基本上去掉其他的,否则它永远不会增加超过500