从单独的后台工作人员更改表单 [英] Changing a form from a separate background worker

查看:38
本文介绍了从单独的后台工作人员更改表单的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个表单,它在加载时启动一个循环后台工作程序,它每半秒从一个 USB 设备获取数据.
一旦程序从 USB 设备接收到一条新数据,它就会运行一个函数.
_Dowork 函数具有

I have a form which when loaded starts a looping background worker which gets data from a usb device every half a second.
Once the program receives a new piece of data from the usb device it runs a function.
The _Dowork function has

while (true)
{
    portConnection.Write("?");
    Thread.Sleep(50);
}

然后我有一个单独的例程在接收到数据时运行

I then have a separate routine that runs when data is received

private void portConnection_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
}

这是无法在原始表单上设置值的例程,因为该函数显然位于单独的线程上.
我怎样才能让这个例程能够影响原始形式?

This is the routine that cannot then set values on the original form as the function is apparently on a separate thread.
How can I make this routine able to influence the original form?

推荐答案

试试这个:

private void InvokeIfRequired(Control target, Delegate methodToInvoke)
{
    if (target.InvokeRequired)
        target.Invoke(methodToInvoke);
    else
        methodToInvoke.DynamicInvoke();
}

在您的 ProcessStatsReceived 中调用方法并在 methodToInvoke 中执行您的操作...

Call the method in your ProcessStatsReceived and in the methodToInvoke do your stuff...

您可以在 ProcessStatusReceived 中像这样使用它:

You can use it like this in the ProccessStatusReceived:

InvokeIfRequired(this, new MethodInvoker(delegate() { this.lblStatus.Text = (string)e.Data; }));

这篇关于从单独的后台工作人员更改表单的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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