public int EndCalculate(ref string resultStr, IAsyncResult ar) { CalculateAsyncResult result = ar as CalculateAsyncResult; if (Interlocked.CompareExchange(ref result.EndCallCount, 1, 0) == 1) { throw new Exception("End方法只能调用一次。"); } result.AsyncWaitHandle.WaitOne(); resultStr = result.ResultStr; return(result.FinnalyResult); }
/// <summary> /// 异步进行耗时计算 /// </summary> /// <param name="ob">CalculateAsyncResult实例本身</param> private static void AsyncCalculate(object obj) { CalculateAsyncResult _asyncResult = obj as CalculateAsyncResult; Thread.SpinWait(1000); _asyncResult.FinnalyResult = _asyncResult._calcNum1 * _asyncResult._calcNum2; _asyncResult.ResultStr = _asyncResult.FinnalyResult.ToString(); // 是否同步完成 _asyncResult._completedSynchronously = false; _asyncResult._isCompleted = true; ((ManualResetEvent)_asyncResult.AsyncWaitHandle).Set(); if (_asyncResult._userCallback != null) { _asyncResult._userCallback(ref _asyncResult.ResultStr, _asyncResult); } }
public IAsyncResult BeginCalculate(int num1, int num2, RefAsyncCallback userCallback, object asyncState) { CalculateAsyncResult result = new CalculateAsyncResult(num1, num2, userCallback, asyncState); return(result); }