Fixed an issue with task asyn loading waiting

修复Task异步加载一直等待的问题。
pull/4/head
hevinci 2022-04-21 21:27:53 +08:00
parent f3ab8f63e7
commit c836dce54d
1 changed files with 13 additions and 18 deletions

View File

@ -1,5 +1,6 @@
using System.Collections; using System.Collections;
using System.Collections.Generic; using System.Collections.Generic;
using System.Threading.Tasks;
namespace YooAsset namespace YooAsset
{ {
@ -106,6 +107,7 @@ namespace YooAsset
public virtual void Destory() public virtual void Destory()
{ {
IsDestroyed = true; IsDestroyed = true;
_taskCompletionSource = null;
} }
/// <summary> /// <summary>
@ -197,31 +199,22 @@ namespace YooAsset
/// <summary> /// <summary>
/// 异步操作任务 /// 异步操作任务
/// </summary> /// </summary>
public System.Threading.Tasks.Task<object> Task public Task<object> Task
{ {
get get
{ {
var handle = WaitHandle; if(_taskCompletionSource == null)
return System.Threading.Tasks.Task.Factory.StartNew(o =>
{ {
handle.WaitOne(); _taskCompletionSource = new TaskCompletionSource<object>();
return AssetObject as object; if (IsDone)
}, this); _taskCompletionSource.SetResult(this);
}
return _taskCompletionSource.Task;
} }
} }
#region 异步编程相关 #region 异步编程相关
private System.Threading.EventWaitHandle _waitHandle; private TaskCompletionSource<object> _taskCompletionSource;
private System.Threading.WaitHandle WaitHandle
{
get
{
if (_waitHandle == null)
_waitHandle = new System.Threading.EventWaitHandle(false, System.Threading.EventResetMode.ManualReset);
_waitHandle.Reset();
return _waitHandle;
}
}
protected void InvokeCompletion() protected void InvokeCompletion()
{ {
// 注意:创建临时列表是为了防止外部逻辑在回调函数内创建或者释放资源句柄。 // 注意:创建临时列表是为了防止外部逻辑在回调函数内创建或者释放资源句柄。
@ -233,7 +226,9 @@ namespace YooAsset
hande.InvokeCallback(); hande.InvokeCallback();
} }
} }
_waitHandle?.Set();
if(_taskCompletionSource != null)
_taskCompletionSource.TrySetResult(this);
} }
#endregion #endregion
} }