gpt4 book ai didi

c# - 在不阻塞 UI 线程的情况下异步使用 HttpWebRequest

转载 作者:行者123 更新时间:2023-11-30 16:19:36 25 4
gpt4 key购买 nike

我正在尝试在 WinForms 应用程序中异步使用 HttpWebRequestHttpWebResonse 而不阻塞我的 UI 线程。

我看到了这个similar SO Question这解释了如何去做。但是,我不是 100% 确定接受的答案是正确的方法。接受的答案是使用 BeginGetResponse

根据MSDN documentation :

The BeginGetResponse method requires some synchronous setup tasks to complete (DNS resolution, proxy detection, and TCP socket connection, for example) before this method becomes asynchronous. As a result, this method should never be called on a user interface (UI) thread because it might take some time, typically several seconds.

谁能给我提供正确的方法来做到这一点。这是我试图在不阻塞 UI 线程的情况下“正常”工作的 C# 函数:

    private IDictionary<string, object> CreateWebRequest(string endPoint, string method, string data, bool addAuthHeader)
{
var req = (HttpWebRequest)WebRequest.Create(endPoint);
req.Method = method;
if (addAuthHeader)
{
req.Headers.Add(HttpRequestHeader.Authorization, "Bearer " + _accessToken.AccessToken);
}

if (!string.IsNullOrEmpty(data))
{
var utfenc = new UTF8Encoding();
byte[] buffer = utfenc.GetBytes(data);
req.ContentLength = buffer.Length;
req.ContentType = "application/x-www-form-urlencoded";

using (Stream strm = req.GetRequestStream())
{
strm.Write(buffer, 0, buffer.Length);
strm.Close();
}
}

HttpWebResponse response = null;
try
{
response = (HttpWebResponse)req.GetResponse();
}
catch (WebException e)
{
if (_accessToken == null)
{
throw;
}
var responseError = (HttpWebResponse)e.Response;
if (responseError.StatusCode == HttpStatusCode.Unauthorized)
{
var stackTrace = new StackTrace();
var q = stackTrace.GetFrame(1).GetMethod().Name;
RefreshAccessCode();

req = (HttpWebRequest)WebRequest.Create(endPoint);
req.Method = method;
if (addAuthHeader)
{
req.Headers.Add(HttpRequestHeader.Authorization, "Bearer " + _accessToken.AccessToken);
}
response = (HttpWebResponse)req.GetResponse();
}
}

string jsonResponse = null;

if (response != null)
using (Stream stream = response.GetResponseStream())
{
if (stream != null)
{
using (var reader = new StreamReader(stream))
{
jsonResponse = reader.ReadToEnd();
}
}
}

return DeserializeResponse(jsonResponse);
}

最佳答案

如果您对 WebRequest 以外的东西持开放态度,我是 System.Net.WebClient 的粉丝.它使用 System.Threading.Tasks 而不是 BeginGetResponse() 和 EndGetResonse()。

public async Task<Dictionary<string, object>> CreateWebRequest(string endPoint, string method, string data, bool addAuthHeader)
{
WebClient client = new WebClient();

if (addAuthHeader)
{
client.Headers.Add(HttpRequestHeader.Authorization, "Bearer " + _accessToken.AccessToken);
}

byte[] buffer = null;

if (!string.IsNullOrEmpty(data))
{
var utfenc = new UTF8Encoding();
buffer = utfenc.GetBytes(data);
}
else
{
buffer = new byte[0];
}

return await client.UploadDataTaskAsync(endPoint, method, buffer)
.ContinueWith((bytes) =>
{
string jsonResponse = null;

using (var reader = new StreamReader(new MemoryStream(bytes)))
{
jsonResponse = reader.ReadToEnd();
}

return DeserializeResponse(jsonResponse);
});
}
}

关于c# - 在不阻塞 UI 线程的情况下异步使用 HttpWebRequest,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15099038/

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