是否可以强制 UI 线程停止等待任务完成,通过 Dispatcher 更新 UI 控件,然后让 UI 恢复到等待任务完成?
我刚刚尝试了以下代码,但它似乎不起作用
UpdatePB(int NewValue)
方法正在由非 UI 线程执行。
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Threading.Tasks;
using System.Threading;
using System.Windows.Threading;
using System.Windows.Threading;
namespace UpdateControlViaDispatcherUITaskWaitAll
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
public void UpdatePB(int NewValue)
{
pb1.Value = NewValue;
}
private void btn1_Click(object sender, EventArgs e)
{
Task tk = Task.Factory.StartNew(() =>
{
Worker();
});
tk.Wait();
}
public void Worker()
{
int currentValue = 0;
for (int i = 0; i < 100; i++)
{
currentValue = i;
Dispatcher.CurrentDispatcher.Invoke(new Action(() =>
{
UpdatePB(currentValue);
}));
Thread.Sleep(1000);
}
}
}
}