来自多个线程的事件调用

时间:2017-09-18 07:18:46

标签: c# .net

我有以下代码:

public class Messenger
{
    public event EventHandler<MessageReceivedEventArgs> MessageReceived;

    public void OnPrivateMessage(string message)
    {
        if (MessageReceived != null)
        {
            MessageReceived(this, new MessageReceivedEventArgs(message));
        }
    }

    public void OnPublicMessage(string message)
    {
        if (MessageReceived != null)
        {
            MessageReceived(this, new MessageReceivedEventArgs(message));
        }
    }
}

从不同的线程调用OnPrivateMessage和OnPublicMessage。从不同的线程调用相同的事件是否安全?

1 个答案:

答案 0 :(得分:0)

快速而肮脏的方式就是锁定。放置该锁的最佳位置可能是在MessageReceived方法中,因此无论何时调用该方法,它都会启动。这样的事情:

private object _messageReceivedLock = new object();

private void MessageReceived(Sender object, MessageReceivedEventArgs msg)
{
    lock (_messageReceivedLock)
    {
        // the rest of the MessageReceived body goes here
    }
}