Mar*_*ijn 2 c# user-interface task-parallel-library tpl-dataflow
我目前正在处理一个从大型二进制文件读取的应用程序,该文件包含数千个文件,每个文件都由应用程序中的其他类处理.该类返回一个对象或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);
Run Code Online (Sandbox Code Playgroud)
上面的代码冻结了我的Form,即使我使用"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);
}
});
Run Code Online (Sandbox Code Playgroud)
我是整个TPL数据流的新手,所以我希望有人可以分享一下为什么在第二个代码片段中它起作用,而在第一个代码片段中却没有.
亲切的问候,Martijn
你的UI被阻塞的原因是becase的你使用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);
}
});
Run Code Online (Sandbox Code Playgroud)
但更好的解决方案是,如果您进行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);
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
3841 次 |
最近记录: |