一段时间后抛出异常

问题描述 投票:0回答:1

我正在通过url使用put命令连接到设备。但是,安装程序要求异步命令位于计时器内。它运行正常一段时间然后mscorlib.dll开始抛出异常并且命令停止发送。

我试图在timer事件处理程序中添加async并等待调用命令的函数之前但它仍然发生。不是100%确定应该如何,因为计时器不能等待,这种情况发生得非常快。

button click {
_updateTimer = new Timer(_updateInterval);
_updateTimer.Tick += new EventHandler(TimerUpdate_Tick);
Start
}

private async void TimerUpdate_Tick(object sender, System.EventArgs e)
{
   //do other very important stuff that has to be in timer update event
   await myfunction();
}

public static async Task myfunction()
{
    HttpClientHandler handler = new HttpClientHandler();

    using (var httpClient = new HttpClient(handler))
    {
       using (var request = new HttpRequestMessage(new HttpMethod("PUT"), address))
       {
           request.Content = new StringContent("hello");
           var response = await httpClient.SendAsync(request);
           //after some time, it gives an exception on this SendAsync saying connection closed. I did try reconnecting but still gives it again.
        }
    }            
}

我想要的是清除一些缓冲区,如果这是问题,并保持连接活动和请求发送前15秒。我不确定正确使用异步,等待和任务。

谢谢

c# .net timer async-await put
1个回答
2
投票

如果您能够执行一段时间的请求然后它们失败,您可能已经耗尽了可用套接字的数量。当我们为每个请求重复创建和处理HttpClient时,就会发生这种情况。

相反,我们应该创建HttpClient并尽可能长时间地重复使用它。从技术上讲,我们应该在完成它之后处理它,因为它实现了IDisposable,但只要我们不断重复使用它,我们就不会完成它。因此,使用和处理它的正确方法并非100%明确。

documentation说:

HttpClient旨在实例化一次,并在应用程序的整个生命周期中重复使用。为每个请求实例化一个HttpClient类将耗尽重负载下可用的套接字数量。这将导致SocketException错误。下面是一个正确使用HttpClient的示例。

......以及以下示例:

public class GoodController : ApiController
{
    // OK
    private static readonly HttpClient HttpClient;

    static GoodController()
    {
        HttpClient = new HttpClient();
    }
}

另一种选择是使用HttpClient以外的东西。 RestSharp不仅非常容易使用,而且它不使用HttpClient,所以你不必担心处理它。它在内部处理很多这样的事情。

此外,here's the fun article引起了我的注意。

© www.soinside.com 2019 - 2024. All rights reserved.