问题
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:
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.
回答2:
Things have changed a bit since the last answer was posted for this question.
System.Windows.Threading.Dispatcher.BeginInvoke is now Deployment.Current.Dispatcher.BeginInvoke
来源:https://stackoverflow.com/questions/2596801/dispatcher-begininvoke-problems