The calling thread cannot access this object because a different thread owns it (with Dispatcher)

Siqueler

It appears that this question has been asked multiple times before, and the suggestions are always the same... to use a dispatcher. I did, and I'm still getting that error.

        var returnedValue = 0;
        HasConnection = false;
        ConnexionProgressBar = true;
        await Task.Run(async () =>
               {
                   returnedValue = await AddSellInvoice();
                   if (returnedValue != 0)
                   {
                       AddSellItems(returnedValue);
                       AddInstallments(returnedValue);
                       Dispatcher.CurrentDispatcher.Invoke(() =>
                       {
                       // Close?.Invoke(this, EventArgs.Empty);
                   });
                   }
               });

Each one of these functions is running SQLLiteCommand. I insert an invoice, get the returned value, then use that value to execute two more different queries. Everything is working fine without any issues, except the commented code above:

Close?.Invoke(this, EventArgs.Empty);

I know that because the code works fine if I don't run it but returns the following error if I do add it back:

The calling thread cannot access this object because a different thread owns it.**

Now from my understanding and from what I found online, the fix would be to use a Dispatcher, but that's not doing anything. This is the command that opens the dialog, and also what's being triggered whenever Close?.Invoke is called:

await Dispatcher.CurrentDispatcher.Invoke(async () =>
             {

                 var createVenteViewModel = new CreateDialogs.CreateVenteViewModel();
                 var createVenteView = new CreateDialogs.CreateVente(createVenteViewModel);
                 await DialogHost.Show(createVenteView, "MainDialog", (object sender, DialogOpenedEventArgs e) =>
                 {
                     void OnClose(object _, EventArgs args)
                     {

                         createVenteViewModel.Close -= OnClose;
                         e.Session.Close();

                        //  ListeVente.Clear();
                        //  ListeVente = GetListeVente();
                        // _snackbarMessageQueue.Enqueue("La vente a été ajouté avec succée.");

                        //RefreshCommandExecute();
                    }
                     createVenteViewModel.Close += OnClose;
                 });

             });
EldHasp

Quote from Dispatcher.CurrentDispatcher:

Gets the Dispatcher for the thread currently executing and creates a new Dispatcher if one is not already associated with the thread.

That is, you get the Dispatcher of the current thread, which in this case is the thread from the Pool. But you need a dispatcher from the UI element whose Close method you are calling. Assuming that the code you've shown is in the Window Code Behind, it should look like this:

        await Task.Run(async () =>
               {
                   returnedValue = await AddSellInvoice();
                   if (returnedValue != 0)
                   {
                       AddSellItems(returnedValue);
                       AddInstallments(returnedValue);
                       // Dispatcher.CurrentDispatcher.Invoke(() =>
                       Dispatcher.Invoke(() =>
                       {
                            Close?.Invoke(this, EventArgs.Empty);
                       });
                   }
               });

But, if you look more deeply, then I don’t see any point in using the Dispatcher here. You are accessing it on the last line of asynchronous code that is executed with await. Therefore, without losing functionality, you can simply take it out of the achinchronous code:

        await Task.Run(async () =>
               {
                   returnedValue = await AddSellInvoice();
                   if (returnedValue != 0)
                   {
                       AddSellItems(returnedValue);
                       AddInstallments(returnedValue);
                       // Dispatcher.CurrentDispatcher.Invoke(() =>
                       /* Dispatcher.Invoke(() =>
                       {
                            Close?.Invoke(this, EventArgs.Empty);
                       }); */
                   }
               });
        if (returnedValue != 0)
            Сlose?.Invoke(this, EventArgs.Empty);

P.S. If this code is not Code Behind, then you can get the application's main thread dispatcher (this will almost 100% be the element's UI thread) from the property: Application.Current.Dispatcher.

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

From Dev

The calling thread cannot access this object because a different thread owns it, even when using the dispatcher

From

The calling thread cannot access this object because a different thread owns it

From Dev

the calling thread cannot access this object because a different thread owns it wpf

From Dev

The Calling thread cannot access this object because a different thread owns it,WPF

From Dev

WPF: The calling thread cannot access this object because a different thread owns it

From Dev

ReactiveUI WPF - The calling thread cannot access this object because a different thread owns it

From Dev

The calling thread cannot access this object because a different thread owns it - BackgroundWorker error

From Dev

Error:The calling thread cannot access this object because a different thread owns it. Storyboard simulation

From Dev

"The calling thread cannot access this object because a different thread owns it" error when updating UI control from different thread in WPF

From Dev

Getting error The calling thread cannot access this object because a different thread owns it wpf, How to use Dispatch.invovef

From Dev

c# - Changes in cefsharp 79.1.35 (from 75.1.143) creates: 'The calling thread cannot access this object because a different thread owns it.'

From Dev

The thread cannot access an object because a different thread owns it when using wpf

From Dev

Famous the calling thread cannot access this object because a different issue

From Dev

The calling thread cannot access this object even after adding Dispatcher.Invoke

From Dev

Updating image via Dispatcher still gives "different thread owns it" error

From Dev

Different thread owns it in WPF

From Dev

Calling thread cannot access object due to separate thread ownership

From Dev

Calling thread cannot access object when it's created from the same thread

From Dev

"calling thread cannot access this object" exception when working with live visual tree in multithreaded UI WPF app

From Dev

WPF error 'calling thread cannot access this object' trying to play sounds in c# class

From Dev

Why is IllegalMonitorStateException thrown despite the thread calling notifyAll owns the monitor?

From Dev

Is checking the Thread is "UI Thread" before Calling Dispatcher.Invoke redundant?

From Dev

Redshift - user "xyz" cannot be dropped because the user owns some object

From Dev

Getting an interface was marshaled for a different thread Exception with UI thread dispatcher call?

From Java

Calling into a saved java object via JNI from a different thread

From Dev

InvalidOperationException, the calling thread should be STA because

From Dev

Pass object to thread (access object outside thread)

From Dev

Calling a Method in a running Thread Object

From Java

Determine which thread owns a monitor

Related Related

  1. 1

    The calling thread cannot access this object because a different thread owns it, even when using the dispatcher

  2. 2

    The calling thread cannot access this object because a different thread owns it

  3. 3

    the calling thread cannot access this object because a different thread owns it wpf

  4. 4

    The Calling thread cannot access this object because a different thread owns it,WPF

  5. 5

    WPF: The calling thread cannot access this object because a different thread owns it

  6. 6

    ReactiveUI WPF - The calling thread cannot access this object because a different thread owns it

  7. 7

    The calling thread cannot access this object because a different thread owns it - BackgroundWorker error

  8. 8

    Error:The calling thread cannot access this object because a different thread owns it. Storyboard simulation

  9. 9

    "The calling thread cannot access this object because a different thread owns it" error when updating UI control from different thread in WPF

  10. 10

    Getting error The calling thread cannot access this object because a different thread owns it wpf, How to use Dispatch.invovef

  11. 11

    c# - Changes in cefsharp 79.1.35 (from 75.1.143) creates: 'The calling thread cannot access this object because a different thread owns it.'

  12. 12

    The thread cannot access an object because a different thread owns it when using wpf

  13. 13

    Famous the calling thread cannot access this object because a different issue

  14. 14

    The calling thread cannot access this object even after adding Dispatcher.Invoke

  15. 15

    Updating image via Dispatcher still gives "different thread owns it" error

  16. 16

    Different thread owns it in WPF

  17. 17

    Calling thread cannot access object due to separate thread ownership

  18. 18

    Calling thread cannot access object when it's created from the same thread

  19. 19

    "calling thread cannot access this object" exception when working with live visual tree in multithreaded UI WPF app

  20. 20

    WPF error 'calling thread cannot access this object' trying to play sounds in c# class

  21. 21

    Why is IllegalMonitorStateException thrown despite the thread calling notifyAll owns the monitor?

  22. 22

    Is checking the Thread is "UI Thread" before Calling Dispatcher.Invoke redundant?

  23. 23

    Redshift - user "xyz" cannot be dropped because the user owns some object

  24. 24

    Getting an interface was marshaled for a different thread Exception with UI thread dispatcher call?

  25. 25

    Calling into a saved java object via JNI from a different thread

  26. 26

    InvalidOperationException, the calling thread should be STA because

  27. 27

    Pass object to thread (access object outside thread)

  28. 28

    Calling a Method in a running Thread Object

  29. 29

    Determine which thread owns a monitor

HotTag

Archive