简体   繁体   中英

Threading in WCF and Dependency Property (The calling thread cannot access this object because a different thread owns it exception)

Any help will be very appreciated.

We have a WCF service (hosted in IIS) that is calling a method, and inside this method there is a call to a getter of a dependency property (this getter is part of of several dependency properties gathered in a single object and used for all kind of conversions).

We see sometimes, and not consistent, a crash on the WCF service side, with the following exception message:

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

I did some searching and found out a similar problem .

From the reading I understand that there is a scenario in which the getter is called on a different thread, and this is why we don't see this exception all the time.

However, I'm still puzzled about the solution. Does the WCF service has a dispatcher on which I can activate CheckAccess() and then call the Dispatcher.Invoke() method (like in WPF application)?

Can someone please advise?

Thanks,

Elad

ALL DependencyObjects have thread-affinity. They can only be accessed by the thread that instantiated it. Call DependencyObject.CheckAccess() to determine if on correct thread. Here's an example. Even though the code uses a Button, a Button is still a DependencyObject.

private void TryToUpdateButtonCheckAccess(object uiObject)
{
    Button theButton = uiObject as Button;

    if (theButton != null)
    {
        // Checking if this thread has access to the object
        if(theButton.CheckAccess())
        {
            // This thread has access so it can update the UI thread
            UpdateButtonUI(theButton);
        }
        else
        {
            // This thread does not have access to the UI thread
            // Pushing update method on the Dispatcher of the UI thread
            theButton.Dispatcher.BeginInvoke(DispatcherPriority.Normal,
                new UpdateUIDelegate(UpdateButtonUI), theButton);
        }
    }
}

What you can do is create a class in your "primary" thread which inherits from DispatcherObject . That will give you access to the Dispatcher property in WCF.

Since your problem is to do with accessing dependency properties across multiple threads, you could use an STA threading model in your WCF service.

This article describes the approach

http://www.netfxharmonics.com/2009/07/Accessing-WPF-Generated-Images-Via-WCF

The relevant section is near the end of the article. It sounds like he is describing your exact problem.

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