milimoe 915de4bc36
添加加载项热更新功能 (#148)
* 添加加载项热更新功能

* 添加加载项卸载的内部实现,完善示例代码
2026-02-06 09:32:28 +08:00

46 lines
1.3 KiB
C#
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

namespace Milimoe.FunGame.Core.Library.Common.Architecture
{
/// <summary>
/// 该类的工具方法允许在同步方法中安全等待异步任务完成
/// </summary>
public class SyncAwaiter
{
/// <summary>
/// 在同步方法中安全等待一个 Task 完成并获取结果
/// 内部使用 ManualResetEventSlim避免死锁
/// </summary>
public static T WaitResult<T>(Task<T> task)
{
if (task.IsCompleted)
return task.Result;
ManualResetEventSlim mres = new(false);
// 当 task 完成时,设置事件信号
task.ContinueWith(_ =>
{
mres.Set();
}, TaskScheduler.Default);
// 阻塞当前线程直到 task 完成
// 注意:这会阻塞调用线程!
mres.Wait();
// 现在可以安全取 Result不会抛死锁
return task.Result;
}
/// <summary>
/// 无返回值版本
/// </summary>
public static void Wait(Task task)
{
if (task.IsCompleted) return;
ManualResetEventSlim mres = new(false);
task.ContinueWith(_ => mres.Set(), TaskScheduler.Default);
mres.Wait();
}
}
}