1
This commit is contained in:
63
Packages/Runtime~/Unity/Scripts/Http/HttpService.cs
Normal file
63
Packages/Runtime~/Unity/Scripts/Http/HttpService.cs
Normal file
@@ -0,0 +1,63 @@
|
||||
using System;
|
||||
using System.Collections;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics;
|
||||
using System.Net.Http;
|
||||
using System.Threading;
|
||||
using Cysharp.Threading.Tasks;
|
||||
using UnityEditor.Rendering;
|
||||
using UnityEngine;
|
||||
using UnityEngine.Events;
|
||||
using Timer = System.Timers.Timer;
|
||||
|
||||
namespace BITKit.Http
|
||||
{
|
||||
public class HttpService : MonoBehaviour
|
||||
{
|
||||
[Header(Constant.Header.Settings)]
|
||||
[SerializeReference,SubclassSelector] private IReference url;
|
||||
[SerializeField] private double interval;
|
||||
|
||||
[Header(Constant.Header.Output)]
|
||||
[SerializeField] private UnityEvent<string> output;
|
||||
|
||||
[Header(Constant.Header.Debug)]
|
||||
[SerializeField, ReadOnly] private double time;
|
||||
|
||||
private readonly Timer timer = new()
|
||||
{
|
||||
AutoReset = true
|
||||
};
|
||||
private readonly HttpClient _httpClient = new();
|
||||
private CancellationToken _cancellationToken;
|
||||
|
||||
private void Awake()
|
||||
{
|
||||
_cancellationToken = gameObject.GetCancellationTokenOnDestroy();
|
||||
}
|
||||
private void Start()
|
||||
{
|
||||
timer.Interval = interval*1000;
|
||||
timer.Elapsed += (x, y) => OnUpdate();
|
||||
timer.Start();
|
||||
}
|
||||
private void OnDestroy()
|
||||
{
|
||||
timer.Stop();
|
||||
timer.Dispose();
|
||||
}
|
||||
private async void OnUpdate()
|
||||
{
|
||||
Stopwatch stopwatch = new();
|
||||
stopwatch.Start();
|
||||
await _httpClient.GetStringAsync(url.Value);
|
||||
_cancellationToken.ThrowIfCancellationRequested();
|
||||
#if UNITY_EDITOR
|
||||
if (UnityEditor.EditorApplication.isPlaying is false) return;
|
||||
#endif
|
||||
stopwatch.Stop();
|
||||
time =System.TimeSpan.FromMilliseconds(stopwatch.ElapsedMilliseconds).TotalSeconds;
|
||||
output.Invoke(url.Value);
|
||||
}
|
||||
}
|
||||
}
|
Reference in New Issue
Block a user