安全线程将变量返回线程 [英] safe threading returnung a variable to a thread

查看:82
本文介绍了安全线程将变量返回线程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

基本前提:我有一个带有多个文本框的Windows窗体.我还剥离了一个正在执行大量工作的线程.我确实需要不时从线程更新表单的文本框(这不是问题),我还需要不时检索存储在表单文本框中的数据.(问题)线程启动后,所有工作均从该线程完成.在返回时,它总是抛出交叉线程错误.事情应该非常简单...将文本框返回一个数据字符串,该数据字符串将返回到发起对窗体的调用并使用了invoke调用的线程.

Basic premis: I have a windows form with a number of Text Boxes. I also have spun off a thread that is doing much of the work. I do need to , from time to time update the Form''s text boxes from the thread( not a problem ) I also need from time to time to retrieve data that is stored in the Form''s text boxes.(Problem) Once the thread is started all work is done from the thread. On the return it keeps throwing a cross threading error. Something that should be very simple... textBox with a data string being returned to the thread that initiated the call to the form and used the invoke call.

Private object GetText(object text)
{
    TextBox TB = (object)text;
    if(TB.InvokeRequired)
    {
      GetTextBoxCallBack d = new GetTextBoxCallBack(GetText);
      this.Invoke(d, new object[] { text });
    }
      return (object)TB.text;
}



如果我忽略交叉线程错误,那么数据在那里..如何正确将数据返回到线程????



If i ignore the cross threading errir the data is there.. How does one properly return data to a thread????

推荐答案

您无法调用与UI相关的任何东西来自非UI线程.相反,您需要使用System.Windows.Threading.DispatcherInvokeBeginInvoke方法(对于Forms或WPF)或System.Windows.Forms.Control(仅对于Forms).

在我过去的答案中,您将找到有关其工作原理的详细说明和代码示例:
Control.Invoke()与Control.BeginInvoke() [ ^ ],
Treeview扫描仪和MD5的问题 [ 如何将ref参数传递给线程 [ ^ ],
启动后更改线程(生产者)的参数 [ ^ ].

另请参阅有关线程的更多参考资料:
如何获取keydown事件在vb.net中的不同线程上操作 [启用禁用+多线程后控件事件不会触发 [ ^ ].

—SA
You cannot call anything related to UI from non-UI thread. Instead, you need to use the method Invoke or BeginInvoke of System.Windows.Threading.Dispatcher (for both Forms or WPF) or System.Windows.Forms.Control (Forms only).

You will find detailed explanation of how it works and code samples in my past answers:
Control.Invoke() vs. Control.BeginInvoke()[^],
Problem with Treeview Scanner And MD5[^].

A very general approach for data exchange with a thread can be offered with a properly designed thread wrapper. The idea is passing the reference of the wrapper to ("this") to the thread constructor, which allows to avoid parametrized thread start (which incur type casts, which is potentially unreliable) and provided universal access to wrapper members by different threads with proper thread synchronization. Please see my past answers:
How to pass ref parameter to the thread[^],
change paramters of thread (producer) after it started[^].

See also more references on threading:
How to get a keydown event to operate on a different thread in vb.net[^],
Control events not firing after enable disable + multithreading[^].

—SA


这篇关于安全线程将变量返回线程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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