sách gpt4 ai đã đi

c# - 线程之间通过委托(delegate)进行通信?

In lại 作者:行者123 更新时间:2023-12-03 13:20:20 25 4
mua khóa gpt4 Nike

我正在寻找线程间通信的解决方案。
线程 A 是 Windows 应用程序的主线程。我启动了一个独立于线程 a 工作的线程 B,它们不共享代码。但是线程 A 必须得到一些关于线程 b 状态的反馈。我尝试与代表一起解决这个问题。
非常抱歉,我忘了补充说我必须在 .net 3.5、c#、WEC7 上工作

代码很重要

public void OnMyEvent(string foo)
{
MessageBox.Show(foo);
}

在线程a的上下文中执行,我该如何实现
public partial class Form1 : Form
{
//...
public void StartThread(Object obj)
{
new ClassForSecondThread(obj as Parameters);
}

private void button1_Click(object sender, EventArgs e)
{
//ParameterizedThreadStart threadstart = new ParameterizedThreadStart(startThread);
ParameterizedThreadStart threadstart = new ParameterizedThreadStart(StartThread);
Thread thread = new Thread(threadstart);
Parameters parameters = new Parameters(){MyEventHandler = OnMyEvent};
thread.Start(parameters);
}

public void OnMyEvent(string foo)
{
MessageBox.Show(foo);
}
}

//This code is executed in Thread B
public class ClassForSecondThread
{
public ClassForSecondThread(Parameters parameters)
{
if (parameters == null)
return;
MyEventhandler += parameters.MyEventHandler;
DoWork();
}

private void DoWork()
{
//DoSomething
if (MyEventhandler != null)
MyEventhandler.DynamicInvoke("Hello World");// I think this should be executed async, in Thread A
Thread.Sleep(10000);
if (MyEventhandler != null)
MyEventhandler.DynamicInvoke("Hello World again"); // I think this should be executed async, in Thread A
}

public event MyEventHandler MyEventhandler;
}
public class Parameters
{
public MyEventHandler MyEventHandler;
}

public delegate void MyEventHandler(string foo);

1 Câu trả lời

当你想在主 UI 线程上调用 MessageBox 时,你可以使用 Control.Invoke 来实现你想要的。 .

     Invoke((MethodInvoker)(() => MessageBox.Show(foo)));

Invoke方法可以直接在 Form 上调用,并且您不会在委托(delegate)中的线程 B 的上下文中 - 代码将在与 Form 相同的线程上运行。

biên tập:
OP 问题:如果我理解 Control.Invoke 正确,它总是在控件的上下文中起作用?

尽管 Invoke 方法使用 Control(在本例中为表单)来获取运行它的 UI 线程的句柄,但委托(delegate)中的代码并不特定于 UI。如果您想添加更多语句并将其扩展以包含更多内容,只需执行以下操作:
        string t = "hello"; //declared in the form

//Thread B context - Invoke called
Invoke((MethodInvoker)(() =>
{
//Back to the UI thread of the Form here == thread A
MessageBox.Show(foo);
t = "dd";
}));

此外,如果您在多线程环境中更新数据,其中数据可由多个线程访问,那么您将需要调查 sychronization - 对数据应用锁等。

关于c# - 线程之间通过委托(delegate)进行通信?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19587383/

25 4 0
行者123
Hồ sơ cá nhân

Tôi là một lập trình viên xuất sắc, rất giỏi!

Nhận phiếu giảm giá Didi Taxi miễn phí
Mã giảm giá Didi Taxi
Giấy chứng nhận ICP Bắc Kinh số 000000
Hợp tác quảng cáo: 1813099741@qq.com 6ren.com