1

我希望了解其他人编写的一些代码。我大致了解发生了什么,但不完全了解。问题是有问题的代码在另一个线程上运行并在第二个线程上处理一个事件。但是,我需要向用户显示警报,如果我从第二个线程触发警报,它当然不会显示,因为 UI 是在第一个线程上运行的。那么我如何“切换”到第一个线程来传递或编组由第二个线程检索到的我的 biz 对象,以便第一个线程可以处理它并显示警报?我以为你会在这种情况下使用委托,但是委托仍然在第二个线程上触发吗?

这是第二个线程的代码:

public delegate void MessageReceivedEventHandler(object sender, MessageEventArgs args);

public class MessageEventArgs : EventArgs
{
    ...snip...
}

public class MSMQListenerService
{
 ...
  public event MessageReceivedEventHandler MessageReceived;
  ....

   public void Start()
    {
        ...
        //this is where we jump to a second thread as this method is IAsyncResult
        _queue.BeginReceive(); 
        ...
    }
   ....
 }

第一个线程的代码:

....snip...

 x = new MSMQListenerService(@".\private$\abc");
 x.MessageReceived += x_MessageReceived;
 x.FormatterTypes = new Type[] { typeof(LoginStatusMessage) };
 x.Start();

...snip....

void x_MessageReceived(object sender, MessageEventArgs args)
{
 //this handler is running on a different thread???
 //I'm OK with that just need to get the args back to the first thread
}

因此,我发布了我认为相关的代码,而不会压倒帖子。因此,如果缺少某些内容,请告诉我,我一定会立即添加。

TIA JB

4

1 回答 1

1

您已经回答了自己的问题:您需要调用 UI 线程上的调用。

this.BeginInvoke(new Action(() => { MessageBox.Show("THIS WILL SHOW ON UI THREAD"); } ));

或者不使用 lambda 表达式,您可以使用委托:

private void DisplayMessage(string message) 
{ 
   ...
}

private delegate void SomeDelegateThatWillRunOnUIThread(string message);

...

this.BeginInvoke(new SomeDelegateThatWillRunOnUIThread(DisplayMessage), yourMessage);

其中this指的是在 UI 线程上运行的实例。

我强烈建议您阅读本教程以获得更多见解 http://www.codeproject.com/Articles/10311/What-s-up-with-BeginInvoke

于 2013-02-25T07:36:28.243 回答