c#中的自定义事件是发送方对象线程安全的

本文关键字:对象 线程 安全 方对象 自定义 事件 | 更新日期: 2023-09-27 18:12:03

好的,所以我正在实现一组自定义事件。它们将主要在多线程环境中使用,以便在线程之间传递主要的成就。现在我有了这个简单的设置:

public delegate void TestEventHandler(object sender, TestEventArgs e);
public class Test
{
    bool _stopTesting = false;
    int _runs = 0;
    public event TestEventHandler Tester;
    protected virtual void OnTest(TestEventArgs e)
    {
        TestEventHandler hand = Tester;
        if (hand != null)
            hand(this, e);
    }
    public void StartTest()
    {
        while (!_stopTesting)
        {
            _runs++;
            TestEventArgs e = new TestEventArgs(true, 100000);
            OnTest(e);
        }
    }
}
public class TestMe
{
    public void TestMeHard(object sender, TestEventArgs e)
    {
        Test check = sender as Test;
        Console.WriteLine(e.Message);
    }
}

事件参数类在其他地方定义。我的问题是,sender对象是线程安全的吗?请原谅这个古怪的问题,但sender对象是引用还是副本?对于发送方对象的任何更改是否会反映在触发事件的实际对象中?

c#中的自定义事件是发送方对象线程安全的

发送方对象是引用而不是副本。

现在到线程安全问题,这取决于在sender参数中传递的对象。由于发送方对象是通用类型转换,因此需要将其转换为正确的类型才能使用它。它可以表示任何对象,但很难说它是否线程安全。

阅读下面的内容,了解如何编写一个线程安全的类