【发布时间】:2021-05-25 07:49:57
【问题描述】:
我正在使用“Invoke”方法从“Backgroundworker”更新一个文本框。 但是当我“刷新” ui 中的图片框时,'backgroundworker' 线程会锁定。所以只更新ui是没有问题的。对于此示例,计数器不会递增。谢谢。
int counter = 0;
private delegate void SafeCallDelegate(string text);
public Form1()
{
InitializeComponent();
backgroundWorker1.RunWorkerAsync();
}
private void pictureBox1_Paint(object sender, PaintEventArgs e)
{
Thread.Sleep(3000); //do stuff
}
private void btnRefresh_Click(object sender, EventArgs e)
{
pictureBox1.Refresh();
}
private void UpdateTextBox(string text)
{
if (textBox1.InvokeRequired)
{
var d = new SafeCallDelegate(UpdateTextBox);
textBox1.Invoke(d, new object[] { text });
}
else
{
textBox1.Text = text;
}
}
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
while (true)
{
Thread.Sleep(100);
counter++;
UpdateTextBox(counter.ToString());
}
}
【问题讨论】:
-
BackgroundWorkers 不再像 c# 具有良好的 async/await 支持那样普遍。你真的需要 BackgroundWorkers 吗?
-
仅供参考:Stephen Cleary (@StephenC) 有一篇很棒的“Task.Run vs BackgroundWorker”文章:blog.stephencleary.com/2013/05/…
-
事实上,乍一看,我推荐
System.Windows.Forms.Timer:“实现一个定时器,它以用户定义的时间间隔引发一个事件。这个定时器针对在 Windows 窗体中的使用进行了优化应用程序,并且必须在窗口中使用。”