tags:

views:

978

answers:

1

I'm getting "An object reference is required for the non-static field, method, or property 'System.Windows.Threading.Dispatcher.BeginInvoke(System.Action)'" for this code.

private void ResponseCompleted(IAsyncResult result)
    {
        HttpWebRequest request = result.AsyncState as HttpWebRequest;
        HttpWebResponse response = request.EndGetResponse(result) as HttpWebResponse;

        using (StreamReader sr = new StreamReader(response.GetResponseStream()))
        {
            Dispatcher.BeginInvoke( () => {
                try
                {
                    XDocument resultsXml = XDocument.Load(sr);
                    QueryCompleted(new QueryCompletedEventArgs(resultsXml));
                }
                catch (XmlException e)
                {
                    XDocument errorXml = new XDocument(new XElement("error", e.Message));
                    QueryCompleted(new QueryCompletedEventArgs(errorXml));
                }
            });

        }
    }
}
+1  A: 

The error indicates that you need an instance of Dispatcher to call BeginInvoke since it is an instance method. Where you get that instance depends on where you want to dispatch a call.

Perhaps you could try using the static property Dispatcher.CurrentDispatcher to get the instance of the dispatcher for the current thread and then call BeginInvoke on that instance. Either that or somehow get a dispatcher instance to your method from the particular thread you want to call to.

Zach Johnson
Given this is an async callback, and assuming he actually wants to be running the invoked code on the UI thread, Dispatcher.CurrentDispatcher won't actually do what he needs. But you're right under other circumstances (or if I've guessed wrong about his requirements).
itowlson
@itowlson: why won't it work?
Veer
Because if this is an async callback, it's running on a thread pool thread, not the UI thread. So Dispatcher.CurrentDispatcher will create a new Dispatcher for the calling thread, i.e. the thread pool thread. And so the invoked code will run on that newly created Dispatcher's thread, i.e. the calling thread, i.e. the thread pool thread -- not the UI thread. (Of course, my assumptions may be wrong here.)
itowlson
I actually ended up taking a different route. I used the AsyncOperation/AsyncOperationManager to fire the QueryCompleted event on the UI thread. This way I don't need the ugly dispatcher code in my clean viewmodels.
cmaduro