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# 事件(如何)?
基础教程推荐
- MS Visual Studio .NET 的替代品 2022-01-01
- SSE 浮点算术是否可重现? 2022-01-01
- 有没有办法忽略 2GB 文件上传的 maxRequestLength 限制? 2022-01-01
- c# Math.Sqrt 实现 2022-01-01
- 为什么Flurl.Http DownloadFileAsync/Http客户端GetAsync需要 2022-09-30
- rabbitmq 的 REST API 2022-01-01
- 如何在 IDE 中获取 Xamarin Studio C# 输出? 2022-01-01
- 将 XML 转换为通用列表 2022-01-01
- 将 Office 安装到 Windows 容器 (servercore:ltsc2019) 失败,错误代码为 17002 2022-01-01
- 如何激活MC67中的红灯 2022-01-01