-1

I just want to run the Drop action asynchronous to display a busy Dialog while moving large amounts. Because the source collection can only be accessed by the Dispatcher, I need to invoke it.

This way the awaited invoke never finishes / the dialog will never be closed.
Using Invoke instead of InvokeAsync here will cause a NotSupportedException for the same reason mentioned above.

public async void Drop(IDropInfo dropInfo)
{
    MainViewModel.Current.ShowBusyDialog();
    await Task.Run(() =>
    {
        // This would crash:
        // Dispatcher.CurrentDispatcher.Invoke(() =>
        await Dispatcher.CurrentDispatcher.InvokeAsync(() =>
        {
            var data = dropInfo.Data as SomeObject;
            var collection = (ObservableCollection<SomeObject>)
                                   ((ICollectionView) dropInfo.TargetCollection).SourceCollection;
            if (data != null)
            {
                // Operate with collection
            }
            else if (dropInfo.Data is IEnumerable<SomeObject>)
            {
                // Operate with collection
            }
        });
    });
    // Never reaches this point
    MainViewModel.Current.CloseDialog();
}

And this way the UI just freezes, but finishes after work is done:

public async void Drop(IDropInfo dropInfo)
{
    MainViewModel.Current.ShowBusyDialog();
    await Dispatcher.CurrentDispatcher.InvokeAsync(() =>
    {
        var data = dropInfo.Data as SomeObject;
        var collection = (ObservableCollection<SomeObject>)
                               ((ICollectionView) dropInfo.TargetCollection).SourceCollection;
        if (data != null)
        {
            // Operate with collection
        }
        else if (dropInfo.Data is IEnumerable<SomeObject
        {
            // Operate with collection
        }
    });
    MainViewModel.Current.CloseDialog();
}

What am I missing out or how could I get this to work like intended?

EDIT

First thanks to your answers and explanations, very helpful! I tried this now and the collection is at the end of the method updated, the UI won't freezes and the Dialog displays correctly, but the collection won't get updated in the UI neither in the ViewModel.
When I let it operate directly with the collection (on the UI Thread) it will be updated in both directly. Btw. the Drop method is in the matching ViewModel, but there I can only acces the binded collection as read only due to validation and checking etc. So I can only add/remove items by custom methods, that would be overkill.

Here in the awaited Task Resharper says: Implicitly captured closure: collection
And at the awaited invoke: Implicitly captured closure: dropInfo
But that should be ok, because the operation doesnt takte that long.

public async void Drop(IDropInfo dropInfo)
{
    MainViewModel.Current.ShowBusyDialog();

    var collection = (ObservableCollection<SomeObject>)
                            ((ICollectionView) dropInfo.TargetCollection).SourceCollection;
    if (collection == null)
        return;
    // ObservableCollection needed for .Move() extension
    var collectionCopy = new ObservableCollection<SomeObject>(collection.ToList());

    await Task.Run(() =>
    {
        var data= dropInfo.Data as SomeObject;
        if (data!= null)
        {
            // operate with collectionCopy (Move item)
        }
        else if (dropInfo.Data is IEnumerable<SomeObject>)
        {
            // operate with collectionCopy (Move items)
        }
    });

    var dispatcher = Dispatcher.CurrentDispatcher;
    await dispatcher.InvokeAsync(() =>
    {
        collection = collectionCopy;
        // Just tried this but didn't work
        RaisePropertyChanged(nameof(collection));
    });

    // collection is updated at this point

    MainViewModel.Current.CloseDialog();
}

UPDATE ---------------------------------------------------------------------

Created and upload a sample to show the issue: Click

3
  • As in the marked duplicate, and the many other similar questions, for Dispatcher.Invoke() or InvokeAsync() to work, the UI thread must be free to process those calls. If you are calling Drop() on the UI thread and don't return from it, the UI thread is blocked and can't process those calls. Commented Aug 2, 2016 at 17:01
  • @PeterDuniho I don't think that's a duplicate at all, 'cause my question doesn't only focus on the invoke, but more on how my szenario could work. See my updated question
    – user5856424
    Commented Aug 3, 2016 at 6:54
  • You need to figure out what thread you're on. I can't tell you if Drop is called on the UI thread or not. If it is, then you don't need to use the dispatcher with your latest code.
    – user1228
    Commented Aug 3, 2016 at 13:40

2 Answers 2

1

What am I missing out or how could I get this to work like intended?

As others have noted, Task.Run will execute work on a background thread, and Dispatcher.InvokeAsync will turn around and execute work on a UI thread. So, your code is not actually doing any real work anywhere other than the UI thread, which is why it's "blocking".

The cleanest solution is to copy all the necessary information out of the UI objects while on the UI thread, do any background work on the thread pool, and finally (if necessary) copy any results back into the UI objects.

public async void Drop(IDropInfo dropInfo)
{
  MainViewModel.Current.ShowBusyDialog();

  // First, copy the data out of the UI objects.
  List<SomeObject> list;
  var data = dropInfo.Data as SomeObject;
  var collection = (ObservableCollection<SomeObject>)
                               ((ICollectionView) dropInfo.TargetCollection).SourceCollection;
  if (collection != null)
  {
    list = collection.ToList();
  }
  else if (dropInfo.Data is IEnumerable<SomeObject>)
  {
    list = ((IEnumerable<SomeObject>)dropInfo.Data).ToList();
  }

  // Then do the background work.
  await Task.Run(() =>
  {
    // Operate with `list`
  });

  // Finally, update the UI objects after the work is complete.
  MainViewModel.Current.CloseDialog();
}
5
  • Thanks for your example, I updated my question above.. could you take a look?
    – user5856424
    Commented Aug 3, 2016 at 6:51
  • @Daniel: collection is not a data-bound property; it's a local variable. You'll need to update the actual collection property that you're using for data binding. Commented Aug 3, 2016 at 12:45
  • I figured out when I only edit the collection in the Drop method without threading by myself, the UI and Property will be updated instantly. So there it should be a reference? But when I use threading the reference gets lost and collectionwill turn into a copied variable. Even if i set collection without using the Dispatcher to the edited collection by the background thread, Resharper says that that doesn't make sense at all, so at this point the reference is already lost.. you can try it on your own with Gong Framework if you don't believe
    – user5856424
    Commented Aug 4, 2016 at 5:59
  • @Daniel: Please reduce the code to the minimal amount that reproduces the issue. Commented Aug 8, 2016 at 13:23
  • Added a sample project in post.. please have a look
    – user5856424
    Commented Aug 30, 2016 at 6:42
0

You're running all this code on the UI dispatcher

await Dispatcher.CurrentDispatcher.InvokeAsync(() =>

What you NEED to do is...

  1. Run all your work in here await Task.Run(() =>
  2. After you're finished, update the UI using the dispatcher.

By the way, if you're updating bound properties that implement INotifyPropertyChanged, you don't even have to use the dispatcher. Update the properties from whatever thread. The Binding will automatically marshall updates onto the UI thread.

The Dispatcher you're using in your code is the UI Dispatcher. That means, when you dispatch a method onto it, you are executing the method on the UI thread. ONLY ever use the Dispatcher at the last possible moment, and only use it to

  • Update the UI from a different thread
  • Schedule UI work after application lifecycle events (see the DispatcherPriority enum)

One more problem...

Dispatcher.CurrentDispatcher retrieves the ... current dispatcher. What is the current dispatcher? It's the dispatcher for the current thread. In your first example, the current thread is a background thread. You want to use the dispatcher from the UI. Here's the first example, but tweaked...

public async void Drop(IDropInfo dropInfo)
{
    // We are in the UI thread here!
    MainViewModel.Current.ShowBusyDialog();
    // as we are on the UI thread, no worries touching the collection here
    var collection = (ObservableCollection<SomeObject>)
         ((ICollectionView)dropInfo.TargetCollection).SourceCollection;
    // as we are on the UI thread, this is the UI dispatcher.
    var dispatcher = Dispatcher.CurrentDispatcher;
    await Task.Run(() =>
    {
        // We are on a background thread here!
        var data = dropInfo.Data as SomeObject;
        YourResults results = null;
        if (data != null)
        {
            results = WhateverProcessingTakesALongTime();
        }
        else if (dropInfo.Data is IEnumerable<SomeObject>)
        {
            results = SameHereIHaveNoIdea(dropInfo.Data);
        }
        // Now, let's update the UI on the UI thread.
        await dispatcher.InvokeAsync(() =>
        {
            UpdateStuffWithStuff(collection, results);
        });
    });
    MainViewModel.Current.CloseDialog();
}
6
  • When I run the code just in a Task, it throws a NotSupportedException too. The collection is the collection from the DataGrid on the UI, that is bound to an object with a CollectionViewSource which just expands an ObservableCollection. So the UI (DataGrid) want to update the collection property, not my ViewModel or a bound property directly
    – user5856424
    Commented Aug 2, 2016 at 14:35
  • @Daniel Properties that are INotifyPropertyChanged are marshalled automatically. INotifyCollectionChanged collections don't marshall changes automatically, unfortunately. You'll have to complete your work locally in the Task, then update the OC using the Dispatcher.
    – user1228
    Commented Aug 2, 2016 at 14:38
  • So how can I do the work in a Task by not calling by reference? I'm using Gong.DragDrop Framework to bind the Drop handler via attached property.
    – user5856424
    Commented Aug 2, 2016 at 14:44
  • 1
    You need to perform all long-lasting work on a background thread. At the end, once your work is done, you use the Dispatcher to apply updates to the ObservableCollection. Your code doesn't show any long-lasting work, so I can't tell you where the line between what you do on a background thread and what you do on the UI dispatcher exists. Also, I've added one more update to the answer.
    – user1228
    Commented Aug 2, 2016 at 15:22
  • Thanks for explanation and example code, I edited my question with updated code and explanations..
    – user5856424
    Commented Aug 3, 2016 at 6:50

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.