Esempio n. 1
0
        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);
        }
Esempio n. 2
0
        /// <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);
            }
        }
Esempio n. 3
0
        public IAsyncResult BeginCalculate(int num1, int num2, RefAsyncCallback userCallback, object asyncState)
        {
            CalculateAsyncResult result = new CalculateAsyncResult(num1, num2, userCallback, asyncState);

            return(result);
        }