FromCurrentSynchronizationContext,我错过了什么吗?
-
12-12-2019 - |
题
我目前正在工作一个从一个大的二进制文件读取的应用程序,该文件包含数千个文件,每个文件都被应用程序中的其他类处理。此类返回对象或null。我想在主窗体上显示一个进度,但由于某种原因,我无法理解它。
int TotalFound = 0;
var uiScheduler = TaskScheduler.FromCurrentSynchronizationContext;
BufferBlock<file> buffer = new BufferBlock<file>();
DataflowBlockOptions options = new DataflowBlockOptions(){ TaskScheduler = uiScheduler, };
var producer = new ActionBlock<someObject>(largeFile=>{
var file = GetFileFromLargeFile(largeFile);
if(file !=null){
TotalFound++;
buffer.post(file);
lblProgress.Text = String.Format("{0}", TotalFound);
}
}, options);
上面的代码冻结了我的表单,即使我使用"TaskScheduler。FromCurrentSynchronizationContext",为什么?因为当我使用下面的代码时,我的表单更新很好
DataflowBlockOptions options = new DataflowBlockOptions(){ TaskScheduler = uiScheduler, };
var producer = new ActionBlock<someObject>(largeFile=>{
var file = GetFileFromLargeFile(largeFile);
if(file !=null){
Task.Factory.StartNew(() => {
TotalFound++;
buffer.Post(file);
}).ContinueWith(uiTask => {
lblProgress.Text = String.Format("{0}", TotalFound);
},CancellationToken.None, TaskContinuationOptions.None, uiScheduler);
}
});
我是整个TPL数据流的新手,所以我希望有人能分享一些关于为什么在第二个代码段中它可以工作,而在第一个代码段中它不能工作的原因。
亲切的问候, 马蒂因
解决方案
你的UI被阻止的原因是 贝塞斯 你在用 FromCurrentSynchronizationContext
.它会导致代码在UI线程上运行,这意味着如果您正在执行一些长时间运行的操作(很可能),它会冻结 GetFileFromLargeFile()
).
另一方面,你必须运行 lblProgress.Text
在UI线程上。
我不确定你应该设置 lblProgress.Text
直接在这段代码中,它看起来像是太紧密的耦合。但是如果你想这样做,我认为你应该在UI线程上运行那一行:
var producer = new ActionBlock<someObject>(async largeFile =>
{
var file = GetFileFromLargeFile(largeFile);
if (file != null)
{
TotalFound++;
await buffer.SendAsync(file);
await Task.Factory.StartNew(
() => lblProgress.Text = String.Format("{0}", TotalFound),
CancellationToken.None, TaskCreationOptions.None, uiScheduler);
}
});
但更好的解决方案是 GetFileFromLargeFile()
异步并确保它不会在UI线程上执行任何长时间运行的操作(ConfigureAwait(false)
可以帮助你)。如果你这么做了, ActionBlock
可以在UI线程上运行而不会冻结UI:
var producer = new ActionBlock<someObject>(async largeFile =>
{
var file = await GetFileFromLargeFile(largeFile);
if (file != null)
{
TotalFound++;
await buffer.SendAsync(file);
lblProgress.Text = String.Format("{0}", TotalFound)
}
}, options);
不隶属于 StackOverflow