在线程上执行EventHandler

时间:2012-04-13 21:03:36

标签: c# multithreading silverlight event-handling

我正在使用LocalMessageReceiverLocalMessageSender类在两个Silverlight应用程序之间进行通信(一个在浏览器中,另一个在浏览器外)。 我需要在新线程中执行messageReceiver.MessageReceived。 这是我的基本代码:

public MainPage()
{
    LocalMessageReceiver messageReceiver = new LocalMessageReceiver("Msg", ReceiverNameScope.Global, LocalMessageReceiver.AnyDomain);
    messageReceiver.MessageReceived += MessageReceiver_MessageReceived; //I want to execute this in a new Thread.
    messageReceiver.DisableSenderTrustCheck = true;

    try
    {
        messageReceiver.Listen();
    }
    catch (ListenFailedException)
    {
        //to do
    }
}

private void MessageReceiver_MessageReceived(object sender, MessageReceivedEventArgs e)
{
    string command = e.Message;

    switch (command)
    {
        case "SCAN":
            e.Response = Scan(e.Message); //I need to send a response
            break;
        default:
            e.Response = "NULL";
            break;
    }
}

1 个答案:

答案 0 :(得分:0)

这可能就是你想要的......

messageReceiver.MessageReceived += (s, e) => 
    Task.Factory.StartNew(() => MessageReceiver_MessageReceived(s, e));

或使用线程...new Thread(() => MessageReceiver_MessageReceived(s, e)).Start();