0

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

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 命令调用的。

我在哪里误解了什么?什么是正确的等待这样做。

4

1 回答 1

3

没必要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);
} 
于 2013-02-02T19:21:38.463 回答