0

我有以下代码可以使异步调用同步。

我知道,请不要认为这很糟糕,并且仅针对一个特定请求需要以这种方式完成。

当执行 using (var response = request.EndGetResponse(request.BeginGetResponse(null, null))) 时,代码在 Windows Phone 8 中引发异常。

该请求实际上是在 UnhandledException 事件处理程序中调用的。

例外:NotSupportedException

信息:Method is not supported

堆栈跟踪:

在 System.Net.Browser.ClientHttpWebRequest.BeginGetResponse(AsyncCallback 回调,对象状态) 在 Gtas.Core.ServiceRepository.ExecuteGtasRequest(String url, String requestData, Boolean isError, String filePath) 在 Gtas.Core.Helpers.GtasRequestWorker.HandleException(Exception异常, AppEnvironment appEnvironment, GtasPerformance GtasPerformance, LimitedCrashExtraDataList extraData, String filePath) at Gtas_WP8.GtasHandler.UnhandledExceptionsHandler(Object sender, ApplicationUnhandledExceptionEventArgs e) at MS.Internal.Error.CallApplicationUEHandler(Exception e) at MS.Internal.Error.IsNonRecoverableUserException(Exception ex , UInt32& xresultValue)

public void ExecuteRequest(string url, string requestData)
{
    try
    {
        WebRequest request = WebRequest.Create(new Uri(url));
        request.Method = "POST";
        request.ContentType = "application/x-www-form-urlencoded";
        request.Headers["Header-Key"] = "AKey";

        // Convert the string into a byte array.
        byte[] postBytes = Encoding.UTF8.GetBytes(requestData);

        using (var requestStream = request.EndGetRequestStream(request.BeginGetRequestStream(null, null)))
        {
            // Write to the request stream.
            endGetRequestStream.Write(postBytes, 0, postBytes.Length);
        }

        using (var response = request.EndGetResponse(request.BeginGetResponse(null, null))) // NotSupportedException
        {
            using (var streamRead = new StreamReader(response.GetResponseStream()))
            {
                // The Response
                string responseString = streamRead.ReadToEnd();

                if (!string.IsNullOrWhiteSpace(requestDataObjResult.FileName))
                {
                    var fileRepo = new FileRepository();
                    fileRepo.Delete(request.FileName);
                }

                Debug.WriteLine("Response : {0}", responseString);
            }
        }
    }
    catch (WebException webEx)
    {
        WebExceptionStatus status = webEx.Status;
        WebResponse responseEx = webEx.Response;
        Debug.WriteLine(webEx.ToString());
    }    
}

框架是否有可能不允许这样做?

先感谢您。

4

1 回答 1

0

在调用 EndGetResponse 之前,您不需要等到 BeginGetResponse 完成吗?这可能会导致 NotSupportedException。

此外,我遇到了类似的问题。当我尝试使用 null 回调调用 BeginGetResponse 时引发了 NotSupportedException。我通过定义这个来解决这个问题

   (a)=>{}

作为回调。(那是银光)

问候

克里斯托夫

于 2013-10-30T11:42:46.320 回答