我正在为我的UWP项目编写HTTP请求的功能。昨晚我偶然得到了数据,这表明在UWP项目上使用HTTP客户端发出HTTP请求需要的时间比Android上的相同操作要多
至于搜索答案,我发现了另一个类似的问题: UWP http client delay in getting response
所以,我的问题是:是什么让这种延迟发生?仅仅是为了应用框架的差异或其他?
这是我在UWP上的HTTP请求代码:
using ServerMonitor.Controls;
using System;
using System.Diagnostics;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
namespace ServerMonitor.Services.RequestServices
{
public class HTTPRequest : BasicRequest, IRequest
{
private const short HTTPPORT = 80;
private const short HTTPSPORT = 443;
private string requestInfo = null;
public static HTTPRequest Instance
{
get
{
return Nested.instance;
}
}
private TransportProtocol httpOrhttps = TransportProtocol.http;
public string Uri { set => uri = value; }
public TransportProtocol ProtocolType { set => httpOrhttps = value; }
public string RequestInfo { get => requestInfo; }
private HTTPRequest() { }
private async Task<bool> HttpRequest(string uri)
{
Stopwatch stopwatch = new Stopwatch();
try
{
HttpClientHandler handler = new HttpClientHandler
{
AllowAutoRedirect = true
};
using (HttpClient client = new HttpClient(handler))
{
client.DefaultRequestHeaders.Referrer = new Uri(uri);
client.Timeout = TimeSpan.FromSeconds(OverTime);
CancellationTokenSource cts = new CancellationTokenSource();
cts.CancelAfter(TimeSpan.FromSeconds(OverTime));
HttpResponseMessage message = null;
stopwatch.Start();
Task queryTask = Task.Run(async() =>
{
message = await client.GetAsync(uri, cts.Token);
stopwatch.Stop();
});
var ranTask = Task.WaitAny(queryTask, Task.Delay(OverTime));
if (0 != ranTask)
{
stopwatch.Stop();
if (!cts.IsCancellationRequested) {
cts.Cancel();
}
TimeCost = OverTime;
Status = "1002";
Exception e = new TaskCanceledException("Overtime");
requestInfo = e.ToString();
ErrorException = e;
return false;
}
if (null == message)
{
Status = "500";
TimeCost = (int)(OverTime * 1.5);
requestInfo = "Failed Request : Response Message Is Null";
}
else {
TimeCost = (int)stopwatch.ElapsedMilliseconds;
Status = ((int)Enum.Parse(typeof(System.Net.HttpStatusCode), message.StatusCode.ToString())).ToString();
requestInfo = string.Format("{0} in {1}ms",message.StatusCode, stopwatch.ElapsedMilliseconds);
Debug.WriteLine(requestInfo);
}
}
await Task.CompletedTask;
return true;
}
catch (TaskCanceledException e)
{
Debug.WriteLine("请求超时");
DBHelper.InsertErrorLog(e);
TimeCost = OverTime;
Status = "1002";
ErrorException = e;
requestInfo = "Request OverTime !";
return false;
}
catch (OperationCanceledException e)
{
Debug.WriteLine("请求失败" + e.Message);
DBHelper.InsertErrorLog(e);
TimeCost = (int)(OverTime*1.5);
ErrorException = e;
Status = "1002";
requestInfo = e.Message;
return false;
}
catch (Exception e)
{
Debug.WriteLine("请求失败" + e.Message);
DBHelper.InsertErrorLog(e);
TimeCost = (int)(OverTime * 1.5);
ErrorException = e;
Status = "1001";
requestInfo = e.Message;
return false;
}
}
public async Task<bool> MakeRequest()
{
bool result = false;
switch (httpOrhttps)
{
case TransportProtocol.http:
result = await HttpRequest(uri);
return result;
default:
return result;
}
}
private class Nested
{
static Nested()
{
}
internal static readonly HTTPRequest instance = new HTTPRequest();
}
}
public enum TransportProtocol
{
http,
https
};
}
接下来是我的一些屏幕截图:
我的UWP环境:
Windows 10.16299 SDK + Framework 4.6 + Visual Studio 2017