简体   繁体   中英

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. 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? 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. 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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