如何将值从一个线程传递到另一个线程 [英] How to pass a value from one thread to another thread

查看:266
本文介绍了如何将值从一个线程传递到另一个线程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们现在必须并行运行线程,如何将一个线程中的值传递给另一个线程.请帮帮我.

We are having to thread running in parallel now how to pass a value from one thread to another thread.Please help me out.

推荐答案

线程间同步和传递数据的不同方案.使用最广泛的模式之一是使用数据队列,尤其是阻塞队列.通过阻塞,可以使预期数据线程与其他线程提供的数据可用性保持同步.它的一个有趣变体是使用委托实例,因此一个线程可以将整个方法与所有要在另一个线程上执行的必需参数(重要的是包括"this")一起传递.

这创建了一种类似于UI线程调用机制的机制(对于System.Windows.Forms和WPF使用System.Windows.Forms.Control.Invoke (BeginInvoke)System.Windows.Threading.Dispatcher实现).但是-注意! —此类调用仅可用于通过各自的UI库的UI线程;对于任意线程,开发人员可以创建类似的机制,我将在下面引用的文章中进行演示.

有关更多详细信息,请参阅我的文章以及完整的源代码和用法示例:
用于线程通信和线程间调用的简单阻塞队列 [ ^ ].

另请参阅本文的替代解决方案,该解决方案适用于.NET Framework 4.0和更高版本.

—SA
There can be many different scenarios of inter-thread synchronization and passing the data. One of the most widely used patterns is using data queues, in particular, blocking queues; the blocking enables synchronization of the thread expecting data with the availability of the data supplied form other thread(s). On interesting variant of it is using delegate instances, so one thread can pass the whole method with all required parameters (importantly, including "this") to be executed on another thread.

This creates a mechanism similar to the UI thread invocation mechanism (implemented for System.Windows.Forms and WPF with System.Windows.Forms.Control.Invoke (BeginInvoke) or System.Windows.Threading.Dispatcher). But — attention! — such invocation is only available for UI threads through respective UI libraries; for the arbitrary threads, the similar mechanism can be created by a developer, which I demonstrate in my article referenced below.

For further detail, please see my article complete with full source code and usage samples:
Simple Blocking Queue for Thread Communication and Inter-thread Invocation[^].

See also the alternative solution to this article which is applicable to .NET Framework 4.0 and later.

—SA


这可能会有所帮助:
线程间通信库 [
this might help:
Inter-Thread Communication Library[^]


这篇关于如何将值从一个线程传递到另一个线程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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