private void Worker(T arg, AsyncOperation asyncOp) { TResult result = default(TResult); Exception error = null; bool cancelled; if (!Cancelled(asyncOp.UserSuppliedState)) { try { result = _func(arg, () => Cancelled(asyncOp.UserSuppliedState), (p) => ReportProgressChanged(p, asyncOp)); } catch (Exception ex) { error = ex; } } cancelled = Cancelled(asyncOp.UserSuppliedState); if (!cancelled) { lock (_userStateToLifetime.SyncRoot) { _userStateToLifetime.Remove(asyncOp.UserSuppliedState); } } AsyncFuncCompletedEventArgs <TResult> e = new AsyncFuncCompletedEventArgs <TResult>(result, error, cancelled, asyncOp.UserSuppliedState); asyncOp.PostOperationCompleted(_onCompleted, e); }
private void CompletedCallback(object operationState) { AsyncFuncCompletedEventArgs <TResult> e = (AsyncFuncCompletedEventArgs <TResult>)operationState; AsyncFuncCompletedEventHandler <TResult> snapshot = Completed; if (snapshot != null) { snapshot(Sender, e); } }
private void Worker(T arg, AsyncOperation asyncOp) { // 进入这个方法表示异步调用已完成。 // 设置标志变量,确保只调用一次,不管是正常完成的回调还是超时回调。 if (Interlocked.CompareExchange(ref _status, 1, 0) == 1) { DisposeTimer(); _isBusy = true; return; } TResult result = default(TResult); Exception error = null; try { if (!_isCancelled) { // Check if function can check for cancellation Func <bool> isCancelled = null; if (_isCancellable) { isCancelled = () => _isCancelled; } // Check if function can report progress Action <int> reportProgress = null; if (_onProgressChanged != null) { reportProgress = (p) => ReportProgressChanged(p, asyncOp); } // Invoke function synchronously result = _func(arg, isCancelled, reportProgress); } } catch (Exception ex) { error = ex; } finally { DisposeTimer(); _isBusy = false; AsyncFuncCompletedEventArgs <TResult> e = new AsyncFuncCompletedEventArgs <TResult>(result, error, _isCancelled, null); asyncOp.PostOperationCompleted(_onCompleted, e); Interlocked.CompareExchange(ref _status, 0, 1); } }