C# Azure.NET Core Appservice由于异步调用而锁定发送502.3
我在Azure应用程序服务中运行的.NET Core 2.X应用程序中运行了此方法。我有一个远程服务器,我们使用这种方法从我们网站上的按钮按钮调用。这就叫远程设备 角度按钮-->Azure中的.NET核心应用程序服务-->另一个应用程序服务-->internet\cell连接设备。我们等待设备的响应返回状态码 如果我快速向这个方法发送命令[2或3秒],它会导致应用程序服务停止响应,直到我重新启动它。我阅读了本文并添加了C# Azure.NET Core Appservice由于异步调用而锁定发送502.3,c#,asp.net-mvc,.net-core,async-await,C#,Asp.net Mvc,.net Core,Async Await,我在Azure应用程序服务中运行的.NET Core 2.X应用程序中运行了此方法。我有一个远程服务器,我们使用这种方法从我们网站上的按钮按钮调用。这就叫远程设备 角度按钮-->Azure中的.NET核心应用程序服务-->另一个应用程序服务-->internet\cell连接设备。我们等待设备的响应返回状态码 如果我快速向这个方法发送命令[2或3秒],它会导致应用程序服务停止响应,直到我重新启动它。我阅读了本文并添加了[,HttpCompletionOption.ResponseHeadersR
[,HttpCompletionOption.ResponseHeadersRead).ConfigureAwait(false)]
但是,我仍然可以冻结整个应用程序,并要求重新启动,以快速向该方法发送命令
private async void SetEndPointValueAsync(string stunnelUrl, string username, string password)
{
try
{
//set the user name and password
var httpClientHandler = new HttpClientHandler()
{
Credentials = new NetworkCredential(username, password)
};
using (var client = new HttpClient(httpClientHandler))
{
using (var response = await client.GetAsync(stunnelUrl**, HttpCompletionOption.ResponseHeadersRead).ConfigureAwait(false)**)
{
if (response.IsSuccessStatusCode)
{
LogInfo(typeof(IntegrationService), stunnelUrl, LogAction.EndpointUpdate);
}
else
{
//request failed.
LogWarning(typeof(IntegrationService), stunnelUrl, LogAction.DeviceRequest);
}
//using (var content = response.Content)
//{
// //do here your changes when required
//}
}
}
}
catch (Exception e)
{
LogErrorDetailed(e, typeof(IntegrationService), stunnelUrl, LogAction.DeviceRequest);
}
}
通常,您不想创建太多的
HttpClient
实例,因为这样会失去它提供的许多管理好处
您可以通过只使用一个实例来减少一些开销,就像这样
private readonly HttpClient _client;
public ClassConstructor(HttpClient client)
{
_client = client ?? new HttpClient();
}
然后你可以改变你的方法,让它看起来像这样
private async Task SetEndPointValueAsync(Uri stunnelUri, string username, string password)
{
if (stunnelUri == null) throw new ArgumentNullException(nameof(stunnelUri));
if (String.IsNullOrEmpty(username)) throw new ArgumentNullException(nameof(username));
if (String.IsNullOrEmpty(password)) throw new ArgumentNullException(nameof(password));
byte[] byteArray = Encoding.ASCII.GetBytes($"{username}:{password}");
string scheme = "Basic";
string parameter = Convert.ToBase64String(byteArray);
HttpRequestMessage request = new HttpRequestMessage();
request.Method = HttpMethod.Post;
request.RequestUri = stunnelUri;
request.Headers.Authorization = new AuthenticationHeaderValue(scheme, parameter);
try
{
HttpResponseMessage response = await _client.SendAsync(request);
// This will throw an HttpRequestException if there is a failure above
response.EnsureSuccessStatusCode();
// do your stuff here...
// { ... }
}
catch (HttpRequestException)
{
// { log your connection / bad request issue. }
}
catch (Exception)
{
// I don't recommend this, but since you had it...
// { handle all other exceptions }
}
}
async void
始终是一个红色标志,除非它是一个事件处理程序。您不返回任务的原因是什么?你怎么称呼这个方法?我们能看到那个密码吗?