使用C#MethodInvoker.Invoke()的GUI应用程序...这是好? [英] Using C# MethodInvoker.Invoke() for a GUI app... is this good?

查看:1951
本文介绍了使用C#MethodInvoker.Invoke()的GUI应用程序...这是好?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

,我有一个GUI应用程序无论从GUI线程或工作线程接收某些事件。

Using C# 2.0 and the MethodInvoker delegate, I have a GUI application receiving some event from either the GUI thread or from a worker thread.

我用下面的方式在表单处理事件:

I use the following pattern for handling the event in the form:

private void SomeEventHandler(object sender, EventArgs e)
{
    MethodInvoker method = delegate
        {
            uiSomeTextBox.Text = "some text";
        };

    if (InvokeRequired)
        BeginInvoke(method);
    else
        method.Invoke();
}

通过使用这种模式,我不重复的实际UI code,但什么我不知道的是,如果这个方法还是不错的。

By using this pattern I do not duplicate the actual UI code but what I'm not sure about is if this method is good.

在具体地,线

method.Invoke()

它使用另一个线程来调用或是否有所转化为直接调用GUI线程的方法?

does it use another thread for invoking or does it translate somewhat to a direct call to the method on the GUI thread?

推荐答案

method.Invoke()调用执行当前执行的线程的委托。使用的BeginInvoke(方法)确保委托调用GUI线程上。

The method.Invoke() call executes the delegate on the current executing thread. Using the BeginInvoke(method) ensures that the delegate is called on the GUI thread.

这是避免code复制时,同样的方法可以从两个GUI线程和其他线程调用的正确途径。

This is the correct way of avoiding code duplication when the same method can be called both from the GUI thread and other threads.

这篇关于使用C#MethodInvoker.Invoke()的GUI应用程序...这是好?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆