C# Events between threads executed in their own thread (How to)?(在自己的线程中执行的线程之间的 C# 事件(如何)?)
问题描述
我想要两个线程.让我们称呼他们:
I'd like to have two Threads. Let's call them :
- 线程 A
- 线程 B
线程 A 触发一个事件,线程 B 监听这个事件.当线程B事件监听器执行时,它是用线程A的线程ID执行的,所以我猜它是在线程A内执行的.
Thread A fires an event and thread B listen to this event. When the Thread B Event Listener is executed, it's executed with the Thread A's thread ID, so i guess it is executed within the Thread A.
我想做的是能够向线程 B 触发事件,说如下:嘿,数据已经为你准备好了,你现在可以处理它了".这个事件必须在它自己的线程中执行,因为它使用了只有他才能访问的东西(比如 UI 控件).
What I'd like to do is be able to fire event to Thread B saying something like: "hey, a data is ready for you, you can deal with it now". This event must be executed in its own Thread because it uses things that only him can access (like UI controls).
我该怎么做?
感谢您的帮助.
推荐答案
您需要将信息编组回 UI 线程.
You'll need to marshal the information back into the UI thread.
通常,您将在事件处理程序中处理此问题.例如,假设线程 A 是您的 UI 线程 - 当它订阅线程 B 中对象上的事件时,事件处理程序将在线程 B 内运行.但是,它可以将其封送回 UI 线程:
Typically, you would handle this in your Event handler. For example, say Thread A was your UI thread - when it subscribed to an event on an object in Thread B, the event handler will be run inside Thread B. However, it can then just marshal this back into the UI thread:
// In Thread A (UI) class...
private void myThreadBObject_EventHandler(object sender, EventArgs e)
{
this.button1.BeginInvoke( new Action(
() =>
{
// Put your "work" here, and it will happen on the UI thread...
}));
}
这篇关于在自己的线程中执行的线程之间的 C# 事件(如何)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:在自己的线程中执行的线程之间的 C# 事件(如何)?


基础教程推荐
- 从 VS 2017 .NET Core 项目的发布目录中排除文件 2022-01-01
- 首先创建代码,多对多,关联表中的附加字段 2022-01-01
- 将事件 TextChanged 分配给表单中的所有文本框 2022-01-01
- 在 VS2010 中的 Post Build 事件中将 bin 文件复制到物 2022-01-01
- JSON.NET 中基于属性的类型解析 2022-01-01
- 如何动态获取文本框中datagridview列的总和 2022-01-01
- 错误“此流不支持搜索操作"在 C# 中 2022-01-01
- 经典 Asp 中的 ResolveUrl/Url.Content 等效项 2022-01-01
- 全局 ASAX - 获取服务器名称 2022-01-01
- 是否可以在 asp classic 和 asp.net 之间共享会话状态 2022-01-01