【发布时间】:2021-07-23 01:27:04
【问题描述】:
我有下面的方法在与主 UI 线程不同的线程上运行,我正在尝试更新主线程上的 ListBox 控件。代码确实有效并且字段确实得到了更新,但是当Invoke 方法运行时,它会切换到主线程。问题是Invoke之后的代码也在主线程上运行,但我需要它在单独的线程上运行。
public static void Status_Message(string str, int destination, int prompt)
{
//Clear_System_Message_Area();
sysmsg++;
ListBox tl = Application.OpenForms["GMLEC"].Controls["groupBox2"].Controls["TestList"] as ListBox;
if (!tl.InvokeRequired)
{
tl.Items.Add(str);
tl.Refresh();
}
else
{
tl.Invoke(new Action<string, int, int>(Status_Message), str, destination, prompt);
}
if (destination == 1)
{
Printer.Output(str);
}
if (prompt == 1)
{
Pause(false);
}
if (sysmsg > 23)
{
Pause(true);
}
}
有没有办法让它回到单独的线程?
【问题讨论】:
-
简单,不要调用整个函数,只调用你需要调用的。我也觉得每个同步调用的人都应该在他们的同行陪审团面前捍卫他们的选择,他们必须一致批准,或者他们需要修复他们的代码。
-
你怎么知道
tl.Invoke之前的代码在后台线程上运行,而在这行之后的代码在主UI线程上运行?我没有看到Thread.CurrentThread.ManagedThreadId被记录在某处。
标签: c# multithreading invoke