gpt4 book ai didi

c# - WP7 应用程序永远不会退出 BeginGetResponse 并进入回调函数

转载 作者:太空狗 更新时间:2023-10-29 21:10:50 26 4
gpt4 key购买 nike

我有以下代码:

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

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

//Console.WriteLine("Please enter the input data to be posted:");
//string postData = Console.ReadLine();
string postData = "my data";

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

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

// Start the asynchronous operation to get the response
IAsyncResult result =
(IAsyncResult)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();

Dispatcher.BeginInvoke((Action)(() => Debug.WriteLine("George")));
}

但是,当我的代码命中 BeginGetResponse 时,它​​永远不会退出(而且我没有命中 GetResponseCallback 函数中的断点)。我尝试添加 BeginInvoke 调用,但我仍然没有进入此方法。此代码可在 Windows 控制台应用程序中运行 - 它在 Windows Phone 7 上不适用

谁能看出我做错了什么?

谢谢。

最佳答案

如果您在 UI 线程上创建了 HttpWebRequest,请确保您没有阻塞 UI 线程,否则可能会死锁。

您链接的桌面 .NET 示例未针对当前电话网络堆栈进行优化。您应该更改代码,以便在后台线程上创建 HttpWebRequest。

关于c# - WP7 应用程序永远不会退出 BeginGetResponse 并进入回调函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4964616/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com