我正在尝试使我的函数异步。我该怎么做?它是一个 HttpWebRequest
private void PostToGoogleChat(string json)
{
HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(_chatUrl);
httpWebRequest.ContentType = "application/json";
httpWebRequest.Method = "POST";
using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
{
streamWriter.Write(json);
}
var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
var result = streamReader.ReadToEnd();
}
}
最佳答案
HttpClient client = new HttpClient();
public async Task PostAsync(string actionName, object json)
{
var content = new StringContent(json.ToString(), Encoding.UTF8,"application/json");
var resultRoles = await client.PostAsync(new Uri(actionName),content);
}
您是新手,所以我不会详细介绍 HttpClient,但应该重用该实例。尝试对如何实现这一点进行一些 self 研究。
关于c# - 如何使 HttpWebRequest 函数异步?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58633347/