简体   繁体   中英

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

Here is a small example of my problem, and I havent been able to solve it from the other questions about the same error.

UI Thread calls a function from a button click that has the following line:

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

AddFileAsync looks like this:

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());
} 

As i have written in the code above, I assumed that the TaskScheduler could make sure it was run on the UI thread. Since the AddFileAsync is called from Databound Buttonclick Command.

Where have i misunderstood something? and what would be the correct wait to do this.

There's no need for StartNew that I can see...

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);
} 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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