105 lines
3.0 KiB
C#
105 lines
3.0 KiB
C#
using Hi.Disp;
|
||
using Hi.Geom;
|
||
using Hi.Native;
|
||
using System.Collections.Concurrent;
|
||
|
||
namespace Hi.Webapi.Services
|
||
{
|
||
/// <summary>
|
||
/// Singleton Service for managing <see cref="DispEngine"/>.
|
||
/// </summary>
|
||
public class RenderingService : IDisposable
|
||
{
|
||
/// <summary>
|
||
/// Engine Dictionary.
|
||
/// Key is sessionID.
|
||
/// </summary>
|
||
public ConcurrentDictionary<string, DispEngine> EngineDictionary { get; } = new();
|
||
ILogger<RenderingService> Logger { get; }
|
||
private bool disposedValue;
|
||
|
||
public RenderingService(ILogger<RenderingService> logger)
|
||
{
|
||
Logger = logger;
|
||
}
|
||
|
||
/// <summary>
|
||
/// 創建或獲取一個 DispEngine 實例
|
||
/// </summary>
|
||
public DispEngine GetOrCreateEngine(string sessionId)
|
||
{
|
||
return EngineDictionary.GetOrAdd(sessionId, id =>
|
||
{
|
||
Logger.LogInformation($"創建新的 DispEngine,SessionId: {id}");
|
||
var engine = new DispEngine();
|
||
engine.BackgroundColor = new Vec3d(0.1, 0.1, 0.5);
|
||
engine.BackgroundOpacity = 0.1;
|
||
return engine;
|
||
});
|
||
}
|
||
|
||
/// <summary>
|
||
/// 移除指定的 DispEngine
|
||
/// </summary>
|
||
public bool RemoveEngine(string sessionId)
|
||
{
|
||
if (EngineDictionary.TryRemove(sessionId, out var engine))
|
||
{
|
||
Logger.LogInformation($"移除 DispEngine,SessionId: {sessionId}");
|
||
|
||
try
|
||
{
|
||
// 停止渲染
|
||
engine.IsVisible = false;
|
||
|
||
// 釋放資源
|
||
engine.Dispose();
|
||
}
|
||
catch (Exception ex)
|
||
{
|
||
Logger.LogError(ex, $"清理 DispEngine 時發生錯誤,SessionId: {sessionId}");
|
||
}
|
||
|
||
return true;
|
||
}
|
||
return false;
|
||
}
|
||
|
||
/// <summary>
|
||
/// 獲取當前活動的引擎數量
|
||
/// </summary>
|
||
public int GetActiveEngineCount() => EngineDictionary.Count;
|
||
/// <inheritdoc/>
|
||
protected virtual void Dispose(bool disposing)
|
||
{
|
||
if (!disposedValue)
|
||
{
|
||
if (disposing)
|
||
{
|
||
foreach (var kvp in EngineDictionary)
|
||
{
|
||
try
|
||
{
|
||
kvp.Value.IsVisible = false;
|
||
kvp.Value.Dispose();
|
||
}
|
||
catch (Exception ex)
|
||
{
|
||
Logger.LogError(ex, $"Dispose 時清理引擎錯誤,SessionId: {kvp.Key}");
|
||
}
|
||
}
|
||
EngineDictionary.Clear();
|
||
}
|
||
|
||
disposedValue = true;
|
||
}
|
||
}
|
||
/// <inheritdoc/>
|
||
public void Dispose()
|
||
{
|
||
Dispose(disposing: true);
|
||
GC.SuppressFinalize(this);
|
||
}
|
||
|
||
}
|
||
} |