简体   繁体   English

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

[英]Custom events in C# specifically is the sender object thread safe

Ok so I am working on implementing a set of custom events. 好的,所以我正在实现一组自定义事件。 They will primarially be used withing a multi-threaded environment to communicate major accomplishments throughout the threads. 首先,它们将与多线程环境一起使用,以在整个线程中传达主要成就。 Now I have this simple set up for now: 现在,我现在有一个简单的设置:

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);
    }
}

The event args class is defined elsewhere. 事件args类在其他地方定义。 My question is this, is the sender object thread safe, and forgive the noobish question but is the sender object a reference or a copy? 我的问题是, sender对象线程是否安全,并且原谅这个笨拙的问题,但是sender对象是引用还是副本? As in will any changesto the sender object be refelected in the actual object that triggered the event? 就像在触发事件的实际对象中一样,对发送方对象的任何更改都将被反映出来吗?

The sender object is a reference and Not a copy. 发件人对象是参考,而不是副本。

Now to the thread safety issue, it depends on what object is passed in the sender argument. 现在到线程安全问题,它取决于在sender参数中传递的对象。 As the sender objects is generically casted, it requires to be casted to proper type to use it. 由于发送方对象是一般类型的,因此需要将其转换为适当的类型才能使用它。 It can represent any object to it is difficult to say if it thread safe or not. 它可以表示任何对象,很难说它是否安全。

Go through this to understand how to write a thread safe class 通过这篇文章了解如何编写线程安全类

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM