0

我有以下类(我取自网上的一个例子,我唯一修改的是我使用 IP 地址和端口而不是域名):

public class ConnectionManager
{
    private static ManualResetEvent allDone = new ManualResetEvent(false);
    private string message = "foobar";

    public Action MessageSent;
    public Action<string> MessageReceived;
    public void SendMessage()
    {
          // Create a new HttpWebRequest object.
        HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://10.1.91.48:3330/");

        request.ContentType = "application/json; charset=utf-8";
        request.Accept = "application/json";
        // Set the Method property to 'POST' to post data to the URI.
        request.Method = "POST";

        // start the asynchronous operation
        request.BeginGetRequestStream(new AsyncCallback(GetRequestStreamCallback), request);
        MessageSent();
        // Keep the main thread from continuing while the asynchronous 
        // operation completes. A real world application 
        // could do something useful such as updating its user interface. 
        allDone.WaitOne();
    }
    private void GetRequestStreamCallback(IAsyncResult asynchronousResult)
    {
        HttpWebRequest request = (HttpWebRequest)asynchronousResult.AsyncState;

        // End the operation
        Stream postStream = request.EndGetRequestStream(asynchronousResult);


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

        // Write to the request stream.
        postStream.Write(byteArray, 0, byteArray.Length);
        postStream.Close();

        // Start the asynchronous operation to get the response
        request.BeginGetResponse(new AsyncCallback(GetResponseCallback), request);
    }

    private void GetResponseCallback(IAsyncResult asynchronousResult)
    {
        HttpWebRequest request = (HttpWebRequest)asynchronousResult.AsyncState;

        // End the operation
        HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(asynchronousResult);
        Stream streamResponse = response.GetResponseStream();
        StreamReader streamRead = new StreamReader(streamResponse);
        string responseString = streamRead.ReadToEnd();
        Console.WriteLine(responseString);
        // Close the stream object
        streamResponse.Close();
        streamRead.Close();

        // Release the HttpWebResponse
        response.Close();
        allDone.Set();

        MessageReceived(responseString);
    }
}

上面的代码无法发送消息。如果我迈步,当我在 GetRequestStreamCallback 内部时,我可以在 IAsyncResult 内部看到以下错误:

AsyncWaitHandle = 'asynchronousResult.AsyncWaitHandle' 引发了“System.NotSupportedException”类型的异常

我究竟做错了什么?如何修复此代码?

4

3 回答 3

1

虽然这可能不是您问题的解决方案,但您需要养成将IDisposable对象放入 using 块的习惯,以确保即使发生异常也能清理它们:

private void GetRequestStreamCallback(IAsyncResult asynchronousResult)
{
    HttpWebRequest request = (HttpWebRequest)asynchronousResult.AsyncState;

    // End the operation
    using (Stream postStream = request.EndGetRequestStream(asynchronousResult))
    {
        byte[] byteArray = Encoding.UTF8.GetBytes(message);

        // Write to the request stream.
        postStream.Write(byteArray, 0, byteArray.Length);
        postStream.Close();
    }

    // Start the asynchronous operation to get the response
    request.BeginGetResponse(new AsyncCallback(GetResponseCallback), request);
}

private void GetResponseCallback(IAsyncResult asynchronousResult)
{
    HttpWebRequest request = (HttpWebRequest)asynchronousResult.AsyncState;

    // End the operation
    string responseString;
    using (HttpWebResponse response = (HttpWebResponse) request.EndGetResponse(asynchronousResult))
    {
        using (Stream streamResponse = response.GetResponseStream())
        {
            using (StreamReader streamRead = new StreamReader(streamResponse))
            {
                responseString = streamRead.ReadToEnd();
                Console.WriteLine(responseString);
            }
        }
    }
    allDone.Set();

    MessageReceived(responseString);
}
于 2012-11-18T02:03:36.413 回答
1

作为替代方案,您可以使用 RestSharp。

http://restsharp.org/

它使这种事情变得微不足道。但是,您必须进行一些细微的更改才能使其在 Windows Phone 上运行:

http://www.toncodes.net/blog/async-and-restsharp-for-windows-phone-7/

没有什么太疯狂了。

于 2012-11-18T03:14:01.317 回答
1

我最终使用了 WebClient:

WebClient wc = new WebClient();
wc.DownloadStringCompleted += ReadServerResponse;
wc.DownloadStringAsync(new Uri(url));
于 2012-11-18T08:31:00.750 回答