我有一个简单的方法,用于调用WebRequest,如下面的代码所示。回调总是在NetworkError.WebRequestAlreadyFinished
上点击。我如何修复我的代码,以便从回调中获取信息?
private async void stkWebRequestConnInfo_Tap(object sender, System.Windows.Input.GestureEventArgs e)
{
HttpWebRequest request = WebRequest.CreateHttp("http://bing.com");
IAsyncResult result = (IAsyncResult)request.BeginGetResponse(new AsyncCallback(response_Callback), request);
}
private void response_Callback(IAsyncResult asyncResult)
{
HttpWebRequest request = (HttpWebRequest)asyncResult.AsyncState;
NetworkInterfaceInfo netInterfaceInfo = null;
try
{
netInterfaceInfo = request.GetCurrentNetworkInterface();
request.EndGetResponse(asyncResult);
}
catch (NetworkException e)
{
// Calling GetCurrentNetworkInterface will throw a NetworkException if the WebRequest has already completed.
// To make this call succeed, make a high latency web request call.
if (e.NetworkErrorCode == NetworkError.WebRequestAlreadyFinished)
{
DisplayMessage(AppResources.MainPage_Info_CannotCallWebRequest, AppResources.MainPage_Info_NetworkInterfaceInformation, MessageBoxButton.OK);
return;
}
else if (e.NetworkErrorCode == NetworkError.NetworkSelectionRequirementFailed)
{
DisplayMessage(AppResources.MainPage_Info_ConnectionRequirementFailed, AppResources.MainPage_Info_NetworkInterfaceInformation, MessageBoxButton.OK);
}
}
catch (WebException e)
{
DisplayMessage(AppResources.MainPage_Info_GeneralError, AppResources.MainPage_Info_WebRequestFailed, MessageBoxButton.OK);
}
// Use a StringBuilder to efficiently build up an information text about this
// NetworkInterfaceInfo.
StringBuilder sb = new StringBuilder();
sb.Append(AppResources.MainPage_Info_Name + " ");
sb.AppendLine(netInterfaceInfo.InterfaceName);
sb.Append(AppResources.MainPage_Info_Type + " ");
sb.AppendLine(GetInterfaceTypeString(netInterfaceInfo.InterfaceType));
DisplayMessage(sb.ToString(), AppResources.MainPage_Info_NetworkInterfaceInformation, MessageBoxButton.OK);
}
void DisplayMessage(string text, string caption, MessageBoxButton buttonConfiguration)
{
Dispatcher.BeginInvoke(() =>
{
MessageBox.Show(text, caption, buttonConfiguration);
});
}
答案 0 :(得分:0)
必须从UI线程调用GetCurrentNetworkInterface。因此,使用Dispatcher.BeginInvoke();
包装调用