我有下一个代码,并且工作正常:
private void BtBasicIntroClick(object sender, EventArgs e)
{
var stopwatch = new Stopwatch();
stopwatch.Reset();
stopwatch.Start();
var executionDataflowBlockOptions = new ExecutionDataflowBlockOptions
{
//TaskScheduler = TaskScheduler.FromCurrentSynchronizationContext(),
MaxDegreeOfParallelism = 1
};
var actionBlock = new ActionBlock<int>(s =>
{
//comboBox1.Items.Add((s*3).ToString());
Invoke(new Action(() => comboBox1.Items.Add((s * 3).ToString())));
}, executionDataflowBlockOptions);
var numeros = Enumerable.Range(0, 40000);
foreach (var numero in numeros)
{
actionBlock.Post(numero);
}
Task.Factory.StartNew(() =>
{
actionBlock.Completion.ContinueWith(delegate
{
stopwatch.Stop();
if (InvokeRequired)
{
Invoke(new Action(() =>
label1.Text = stopwatch.ElapsedMilliseconds.ToString(CultureInfo.InvariantCulture)));
}
});
actionBlock.Complete();
actionBlock.Completion.Wait();
});
}
Windows 窗体工作正常......进程不会阻止用户界面
但是,如果我将 MaxDgreeOfParallelism 更改为其他值(2 或 3 或 4...),则 UI 将被阻止,直到进程完成。
我已经在 Visual Studio 中看到了 Parallel Tasks 窗口和 Thread 窗口,在这两种情况下,一切都在工作线程中工作,但在后一种情况下(当 MaxDgreeOfParallelism 它不同于 1 时)UI 直到进程完成才响应
为什么?