繁体   English   中英

我如何使用TaskScheduler.FromCurrentSynchronizationContext()解决后台线程异常上的UI更新

[英]how do i use TaskScheduler.FromCurrentSynchronizationContext() to solve UI update on background thread exception

这是我的问题的一个小例子,我无法从其他有关相同错误的问题中解决。

UI线程从具有以下行的按钮单击中调用函数:

await DataSet.AddFileAsync(String.Format("ms-appdata:///local/IMM_FACE_DB/{0}", file.Name));

AddFileAsync看起来像这样:

public ObservableCollection<Model> Data {get;set;}
public Task AddFileAsync(string path)
{
     return Task.Factory.StartNew((state) =>
     {
         // Here some IO and computation is done, eventually some content is added 
         // to Data. Data is also bound to a GridView and this fails.

         //I assumed that TaskScheduler.FromCurrentSynchronizationContext()
         // would solve this, but it does not.
     }, TaskScheduler.FromCurrentSynchronizationContext());
} 

正如我在上面的代码中所写的那样,我假设TaskScheduler可以确保它在UI线程上运行。 由于AddFileAsync是从Databound Buttonclick命令调用的。

我在哪里误会了什么? 什么是正确的等待时间

我不需要看到StartNew ...

public async Task AddFileAsync(string path)
{
  // Do some IO
  var ioResult = await DoIoAsync(path);

  // Do some computation
  var computationResult = await Task.Run(() => DoComputation(ioResult));

  // Update Data
  Data.Add(computationResult);
} 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM