1
This commit is contained in:
@@ -2,6 +2,7 @@ using Godot;
|
||||
using System;
|
||||
using System.Threading;
|
||||
using BITKit.Packages.Core.LazyLoad;
|
||||
using HttpClient = System.Net.Http.HttpClient;
|
||||
|
||||
namespace BITKit;
|
||||
public partial class HttpGet : Node,IActivable
|
||||
@@ -18,51 +19,47 @@ public partial class HttpGet : Node,IActivable
|
||||
[Signal]
|
||||
public delegate void OnGetEventHandler(string httpContext);
|
||||
/// <summary>
|
||||
/// 最大并行请求数量
|
||||
/// </summary>
|
||||
private readonly LimitTimes limitConcurrent =new (1);
|
||||
/// <summary>
|
||||
/// 请求数据的间隔
|
||||
/// </summary>
|
||||
private readonly IntervalTimer _intervalTimer = new(1);
|
||||
/// <summary>
|
||||
/// http客户端
|
||||
/// </summary>
|
||||
private readonly ServiceLoader<System.Net.Http.HttpClient> httpClient=new();
|
||||
private readonly HttpClient httpClient=new();
|
||||
/// <summary>
|
||||
/// 取消令牌,用于取消Http Get
|
||||
/// </summary>
|
||||
private CancellationToken _cancellationToken;
|
||||
private bool allowNextRequest = true;
|
||||
|
||||
public override void _Ready()
|
||||
{
|
||||
_cancellationToken = new CancellationToken();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 物理帧用于控制并发和间隔的同时请求数据
|
||||
/// </summary>
|
||||
/// <param name="delta"></param>
|
||||
public override void _PhysicsProcess(double delta)
|
||||
{
|
||||
if(Enabled is false)return;
|
||||
if (Enabled is false) return;
|
||||
//等待依赖加载
|
||||
//请求间隔控制+请求并发控制
|
||||
if (_intervalTimer.Allow is false || httpClient.IsLoaded is false) return;
|
||||
if (_intervalTimer.Allow is false) return;
|
||||
//如果url为空
|
||||
if (string.IsNullOrEmpty(url)) return;
|
||||
if (!limitConcurrent.AllowOnly) return;
|
||||
//提交并发
|
||||
limitConcurrent.CanUpdate();
|
||||
//发送请求
|
||||
Request();
|
||||
if (allowNextRequest)
|
||||
Request();
|
||||
}
|
||||
private async void Request()
|
||||
{
|
||||
allowNextRequest = false;
|
||||
//获取json
|
||||
|
||||
try
|
||||
{
|
||||
var json = await httpClient.Value.GetStringAsync(url, _cancellationToken);
|
||||
var json = await httpClient.GetStringAsync(url, _cancellationToken);
|
||||
//取消执行,如果已取消令牌
|
||||
_cancellationToken.ThrowIfCancellationRequested();
|
||||
|
||||
@@ -72,14 +69,11 @@ public partial class HttpGet : Node,IActivable
|
||||
catch (InvalidOperationException)
|
||||
{
|
||||
BIT4Log.Warning(url);
|
||||
//返回并发数量
|
||||
limitConcurrent.Release();
|
||||
}
|
||||
catch (OperationCanceledException)
|
||||
{
|
||||
//返回并发数量
|
||||
limitConcurrent.Release();
|
||||
}
|
||||
allowNextRequest = true;
|
||||
}
|
||||
|
||||
public void SetActive(bool active) => Enabled=active;
|
||||
|
Reference in New Issue
Block a user