Dispatcher.BeginInvoke problems

五迷三道 提交于 2020-01-01 04:30:06

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!