1

I encountered in question without an answer in WPF (C#), I would like some help.

I want to check if an object is created in the main(UI) thread, is there a way to do it?

(Object such as a list, collection, etc.)

EDIT

I am trying to reduce the use of Dispatcher.Invoke (and Dispatcher.CheckAccsess), because it slows down the system.

I have an object that when it binding to the UI I need the Invoke, but many times it was created in a different thread and there is no need in Invoke and it can set from the current thread.

Community
  • 1
  • 1
Hodaya Shalom
  • 4,327
  • 12
  • 57
  • 111

1 Answers1

1

You can do the check in an Extension method:

public static void Invoke<T>(this T c, Action<T> action) where T : Control
{
    if (c.Dispatcher.CheckAccess()))
        control.Dispatcher.Invoke(...)
    else
        action(c);
}

(based on A better way to write extension method to invoke a control?)

Other then using extension methods to create better looking code there is no way to check what tread is used to create an object.

Are you using async/await? Because that might reduce the need to do this. Can you show some code where you are accessing the UI from another thread? Maybe you can reduce that situation.

Community
  • 1
  • 1
Peter Bons
  • 26,826
  • 4
  • 50
  • 74