在C#是什么2个线程之间传递数据的推荐方法? [英] In C# what is the recommended way of passing data between 2 threads?

查看:633
本文介绍了在C#是什么2个线程之间传递数据的推荐方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有我的主界面线程,以及它自己的ApplicationContext内部运行的第二个线程(保持它活着,即使没有要完成的工作)。我想调用一个方法,我从我的GUI线程的线程2次,但如果我只是调用thread.Method();这似乎是对我的主界面线程运行,从而导致我的GUI变得反应迟钝。什么是调用不同的线程方法的最佳方式?

I have my main GUI thread, and a second thread running inside it's own ApplicationContext (to keep it alive, even when there is no work to be done). I want to call a method on my 2nd thread from my GUI thread, but if I just call thread.Method(); it seems to be running on my main GUI thread and causes my GUI to become unresponsive. What is the best way to call methods on different threads?

更新:
我真正希望做的,是2个线程之间进行通信,而不是与一个GUI通信。图形用户界面恰好是需要与我的第二个线程进行通信线程之一。

Update: What I'm really looking to do here is communicate between 2 threads, not communicate with a GUI. The GUI just happens to be one of the threads that will need to communicate with my 2nd thread.

更新#2:
好吧,我必须真正缺少的东西。我创建了一个事件和委托并有我的工作线程订阅事件。但是,当我打电话调用(MyEvent);从我的GUI线程的工作线程不会最终被GUI线程上挂起GUI线程,直到它完成处理工作。正是我试图做甚至有可能,没有投票的静态对象吗?

Update #2: Ok, I must really be missing something. I created an event and a delegate and had my worker thread subscribe to the event. But when I call Invoke(MyEvent); from my GUI thread the work that the worker thread does ends up being on the GUI thread and hangs the GUI thread until it's done processing. Is what I'm trying to do even possible, without polling on a static object?

推荐答案

的.Net已经自带了一个 <一个href=\"http://msdn.microsoft.com/en-us/library/system.componentmodel.backgroundworker.aspx\">System.ComponentModel.BackgroundWorker类专门处理执行后台任务,并以一个GUI进行通信。使用它。

.Net already comes with a System.ComponentModel.BackgroundWorker class specifically to handle performing background tasks and communicating with a GUI. Use it.

这篇关于在C#是什么2个线程之间传递数据的推荐方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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