How do I pass a method call to another thread?

I have the following problem, WPF multithreaded application, implementation of a model view view. Presenters and views that belong to each other are created on a separate thread and receive a separate dispatcher. Now someone is calling a method on the presenter from another thread. I intercept the call and now there is a problem: if the call comes from the same thread as the master, I want to continue the call, otherwise call the Dispatcherthread call so I don't have to worry about the UI. I've already read about using SynchronizationContext, but that doesn't seem to work for me, because if the calling thread is not a UI thread, I can't compare the two contexts. What is a possible, working and elegant solution?

+1


source to share


2 answers


if( presenterDispatcherObject.CheckAccess() )
   Doit();
else
  presenterDispatcherObject.BeginInvoke( DispatcherPriority.Normal, () => DoIt() ); 

      



+3


source


If you want the Dispatcher to block (pending a return), I would use Invoke instead of BeginInvoke. This would rather mimic the behavior of actually calling the function directly. Call blocks that call the thread until the function finishes (more like Win32 SendMessage). BeginInvoke only messages and returns without waiting for a function (such as WinMessage PostMessage) to return.

CheckAccess is slow. I would limit CheckAccess, leaving calls less frequent for different threads.



public delegate bool MyFuncHandler(object arg);

bool ThreadedMyFunc(object arg)
{
    //...

    bool result;

    //...

    // use dispatcher passed in,  I would pass into the contructor of your class
    if (dispatcher.CheckAccess())
    {
        result = MyFunc(arg);
    }
    else
    {
        result = dispatcher.Invoke(new MyFuncHandler(MyFunc), arg);
    }

    return result;
}

bool MyFunc(object arg)
{
    //...
}

      

0


source







All Articles