-
Notifications
You must be signed in to change notification settings - Fork 22
网络超时处理方法
L edited this page Jan 21, 2019
·
3 revisions
网络超时针对双方建立联系的时候,建立联系之后传输数据的时间不算在内
故而如果网络状况不好,但是建立了联系,传输很慢,不会造成网络超时,但是结果可能不尽人意
利用Task进行控制,解决整个请求过程(建立联系+通讯)太长,浪费时间的问题,超过一定时间就中断
//https://docs.microsoft.com/en-us/dotnet/standard/parallel-programming/task-cancellation
//http://www.cnblogs.com/Mainz/archive/2012/03/21/2410699.html
var tokenSource = new CancellationTokenSource();
CancellationToken token = tokenSource.Token;
var task = Task.Factory.StartNew(() =>
{
while (true)
{
if (token.IsCancellationRequested)
{
//此时已经取消任务了
//token.ThrowIfCancellationRequested();
}
else
{
using (HttpClient client = new HttpClient())
{
var response = client.GetAsync(url).Result;
var str = response.Content.ReadAsStringAsync().Result;
}
}
}
}, token);
//等待10s,然后取消任务
if (!task.Wait(10000, token))
{
tokenSource.Cancel();
}
//等待循环到token.IsCancellationRequested=true
Thread.Sleep(5000);
tokenSource.Dispose();
try
{
using (HttpClient client = new HttpClient())
{
//设置超时时间为1s
client.Timeout = new TimeSpan(0, 0, 1);
var response = client.GetAsync(url).Result;
var str = response.Content.ReadAsStringAsync().Result;
}
}
catch(Exception ex)
{
//请求失败,1s后会抛异常到达这里
}