gpt4 book ai didi

winforms - C# Winforms : BeginInvoke still running on same thread?

转载 作者:行者123 更新时间:2023-12-03 13:17:57 33 4
gpt4 key购买 nike

我是网络开发人员,我正在尝试进入多线程编程。
在一种形式上,我尝试使用异步委托(delegate)在第二个线程中运行计算值的方法。
我还希望通知显示 UI 线程中实际进度的进度条。

delegate void ShowProgressDelegate(int total, int value);  
delegate void ComputeDelegate(int value);

//Some method simulating sophisticated computing process
private void Compute(int value)
{
ShowProgress(value, 0);
for (int i = 0; i <= value; i++)
{
ShowProgress(value, i);
}
}

//Method returning values into UI thread
private void ShowProgress(int total, int value)
{
if (!this.InvokeRequired)
{
ComputeButton.Text = value.ToString();
ProgressBar.Maximum = total;
ProgressBar.Value = value;
}
else
{
ShowProgressDelegate showDel = new ShowProgressDelegate(ShowProgress);
this.BeginInvoke(showDel, new object[] { total, value });
}
}


//firing all process
private void ComputeButton_Click(object sender, EventArgs e)
{
ComputeButton.Text = "0";
ComputeDelegate compDel = new ComputeDelegate(Compute);
compDel.BeginInvoke(100000, null, null);
}

当我运行它时,一切都在计算没有任何问题,除了它仍在 UI 线程中运行(我想是这样,因为当我单击表单上的某个按钮时它会卡住)。

为什么?我还附加了具有相同代码的可构建示例项目(VS2010): http://osmera.com/windowsformsapplication1.zip

感谢帮助新手。

最佳答案

在您显示的代码中,除了更新进度条之外,您什么也没做 - 因此有数千条 UI 消息需要编码,但在非 UI 线程中没有发生任何重大事件。

如果您开始在 Compute 中模拟实际工作,我怀疑你会看到它的行为更合理。您需要确保不会像现在这样使用进度更新淹没 UI 线程。

关于winforms - C# Winforms : BeginInvoke still running on same thread?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6110593/

33 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com