线程安全的事件 - 这是一个"洁净QUOT;办法? [英] Thread-safe events - is this a "clean" way?

查看:126
本文介绍了线程安全的事件 - 这是一个"洁净QUOT;办法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我偶然发现了一些代码,在专业图书馆,是不确定的,如果这是处理跨线程事件调用一个清洁的方式。

I stumbled over some code in a professional library and am uncertain if this is a clean way to handle cross-thread event calls.

下面的代码是在窗体应用程序。线程调用是从自身开始一个新的线程和接收消息的类制成:

The code below is in a forms application. Thread calls are made from a class that itself starts a new thread and receives messages:

private void Library_StatusChanged(object sender, AbstractTestCase.StatusChangedEventArgs e)
{
    if (this.InvokeRequired)
    {
        this.lblProgress.Invoke((MethodInvoker)delegate ()
        {
            lblProgress.Text = "Current state: " + e.Step;
            lblProgress.Refresh();
        }
        );

        this.pbProgess.Invoke((MethodInvoker)delegate ()
        {
            pbProgess.Value = e.Percentage;
            pbProgess.Refresh();
        });

        this.lstStatus.Invoke((MethodInvoker)delegate ()
        {
            lstStatus.Items.Add("    " + e.Step);
            lstStatus.Refresh();

        });

        this.Invoke((MethodInvoker)delegate ()
        {
            this.Refresh();
        });
    }
    else
    {
        lblProgress.Text = "Current state:" + e.Step;
        lblProgress.Refresh();

        pbProgess.Value = e.Percentage;
        pbProgess.Refresh();

        lstStatus.Items.Add("    " + e.Step);
        lstStatus.Refresh();

        this.Refresh();
    }

    Application.DoEvents();
}



这是最先进的?在我看来,这是一个有点乱?!

Is this "state of the art"? In my opinion it's a little messy?!

推荐答案

最先进的国家是使用伺机。如果这里是不可能的,至少代码简化到一个调用电话。它不需要调用上的每个控件,随便找个地方调用UI线程上。

State of the art is using await. If that is not possible here, at least simplify the code to a single Invoke call. It is not needed to invoke on each control, just invoke anywhere on the UI thread.

InvokeRequired 检查应没有必要的,因为你要的知道什么线程的事件引发

The InvokeRequired check should not be required because you should know on what thread the event is raised.

在任何情况下,重复的逻辑,如 当前的状态:+ e.Step 确实是一个坏主意,我会在代码审查失败这无论是什么

In any case duplicating logic such as "Current state: " + e.Step is really a bad idea and I would fail this in a code review no matter what.

Application.DoEvents 的存在是一个非常不好的迹象。可能是一种误解,因为它才有意义称呼它在UI线程上,但为什么调用的时候就已经在UI线程上? 。貌似矛盾

The presence of Application.DoEvents is a really bad sign. Probably a misunderstanding because it only makes sense to call it on the UI thread, but why Invoke when already on the UI thread?! Looks like a contradiction.

lstStatus.Refresh(); 也是一种误解,可能是迷信。控制自动刷新(如果允许对事件处理)。

lstStatus.Refresh(); is also a misunderstanding, probably superstitious. Controls refresh automatically (if you allow for event processing).

这篇关于线程安全的事件 - 这是一个"洁净QUOT;办法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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