一段时间后抛出异常

Throwing exception after a while

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

我尝试在定时器事件处理程序中添加异步并在调用命令的函数之前等待,但它仍然发生。不能 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 秒那样发送请求。 我不确定异步、等待和任务是否正确使用。

谢谢

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

相反,我们应该创建 HttpClient 并尽可能长时间地重复使用它。从技术上讲,我们应该在用完它后处理掉它,因为它实现了 IDisposable,但只要我们继续重用它,我们就不会用完它。所以使用和处置它的正确方法并不是 100% 清楚的。

documentation 说:

HttpClient is intended to be instantiated once and re-used throughout the life of an application. Instantiating an HttpClient class for every request will exhaust the number of sockets available under heavy loads. This will result in SocketException errors. Below is an example using HttpClient correctly.

... 下面是这个例子:

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

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

另一种选择是使用 HttpClient 以外的东西。 RestSharp 不仅非常易于使用,而且它不使用 HttpClient,因此您不必担心处理它。它在内部处理很多类似的事情。

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