• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

C# AggregateException类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了C#中AggregateException的典型用法代码示例。如果您正苦于以下问题:C# AggregateException类的具体用法?C# AggregateException怎么用?C# AggregateException使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。



AggregateException类属于命名空间,在下文中一共展示了AggregateException类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的C#代码示例。

示例1: ThrowAsync

        /// <summary>Throws the exception on the thread pool.</summary>
        /// <param name="exception">The exception to propagate.</param>
        /// <param name="targetContext">
        /// The target context on which to propagate the exception; otherwise, <see langword="null"/> to use the thread
        /// pool.
        /// </param>
        internal static void ThrowAsync(Exception exception, SynchronizationContext targetContext)
        {
            if (targetContext != null)
            {
                try
                {
                    targetContext.Post(
                        state =>
                        {
                            throw PrepareExceptionForRethrow((Exception)state);
                        }, exception);
                    return;
                }
                catch (Exception ex)
                {
                    exception = new AggregateException(exception, ex);
                }
            }

#if NET45PLUS
            Task.Run(() =>
            {
                throw PrepareExceptionForRethrow(exception);
            });
#else
            ThreadPool.QueueUserWorkItem(state =>
            {
                throw PrepareExceptionForRethrow((Exception)state);
            }, exception);
#endif
        }
开发者ID:endo0407,项目名称:IteratorTasks,代码行数:37,代码来源:AsyncServices.cs


示例2: ThrowAsync

		internal static void ThrowAsync(Exception exception, SynchronizationContext targetContext)
		{
			if (targetContext != null)
			{
				try
				{
					targetContext.Post(delegate(object state)
					{
						throw AsyncServices.PrepareExceptionForRethrow((Exception)state);
					}, exception);
					return;
				}
				catch (Exception ex)
				{
					exception = new AggregateException(new Exception[]
					{
						exception,
						ex
					});
				}
			}
			ThreadPool.QueueUserWorkItem(delegate(object state)
			{
				throw AsyncServices.PrepareExceptionForRethrow((Exception)state);
			}, exception);
		}
开发者ID:tommybiteme,项目名称:X,代码行数:26,代码来源:AsyncServices.cs


示例3: LogException

 /// <summary>
 /// Function to log exception except disposed exception.
 /// </summary>
 /// <param name="aggregateException">Aggregate Exception</param>
 private static void LogException(AggregateException aggregateException)
 {
     if (aggregateException != null)
     {
         aggregateException.Handle((ex) => HandleException(ex));
     }
 }
开发者ID:JaipurAnkita,项目名称:mastercode,代码行数:11,代码来源:TimerExtensions.cs


示例4: HandleError

 private void HandleError(AggregateException ae)
 {
     if (ae.InnerException != null)
     {
         MessageBox.Show("An error occurred while uploading the image to imgur.com. Please try again.", "SnagitImgur", MessageBoxButtons.OK, MessageBoxIcon.Warning);
         ae.InnerException.ToExceptionless().Submit();
     }
 }
开发者ID:ebmp19,项目名称:SnagitImgur,代码行数:8,代码来源:ShareController.cs


示例5: HandleAggregateException

        Tuple<string, bool> HandleAggregateException(AggregateException aggregrateException,
            ReportExceptionEventArgs et) {
            Tuple<string, bool> handled = null;
            foreach (var error in aggregrateException.Flatten().InnerExceptions) {
                if (handled == null || handled.Item1 == null)
                    handled = InternalHandler(error, et); // Does not set the loader to true
            }

            return handled;
        }
开发者ID:MaHuJa,项目名称:withSIX.Desktop,代码行数:10,代码来源:KnownExceptions.cs


示例6: HandleFault

        public void HandleFault(AggregateException ex)
        {
            Logger.Error(ex.Message, ex);

            var message = IoC.Get<MessageBoxViewModel>();
            message.DisplayName = "Error";
            message.Content = new ErrorInfo();
            message.DismissAction = () => NavigateToHome();
            message.DismissTimeout = 10000;

            NavigateToScreen(message);
        }
开发者ID:edjo23,项目名称:shop,代码行数:12,代码来源:ScreenCoordinator.cs


示例7: HandleException

 private static void HandleException(AggregateException ex)
 {
     if (ex.InnerExceptions.OfType<TaskCanceledException>()
           .Any())
     {
         Console.WriteLine("Task was canceled...");
         Log.Trace("Task was canceled");
     }
     else
     {
         Log.Error(ex, "Task proccessing exception");
     }
 }
开发者ID:matafonoff,项目名称:Brokeree.Test,代码行数:13,代码来源:Program.cs


示例8: SimpleInnerExceptionTestCase

		public void SimpleInnerExceptionTestCase ()
		{
			var message = "Foo";
			var inner = new ApplicationException (message);
			var ex = new AggregateException (inner);

			Assert.IsNotNull (ex.InnerException);
			Assert.IsNotNull (ex.InnerExceptions);

			Assert.AreEqual (inner, ex.InnerException);
			Assert.AreEqual (1, ex.InnerExceptions.Count);
			Assert.AreEqual (inner, ex.InnerExceptions[0]);
			Assert.AreEqual (message, ex.InnerException.Message);
		}
开发者ID:bradchen,项目名称:mono,代码行数:14,代码来源:AggregateExceptionTests.cs


示例9: EventForFailedOperation

        internal static IProvisioningEvent EventForFailedOperation(AggregateException exception)
        {
            HttpStatusCode httpStatus;
            if (ProvisioningErrorHandling.TryGetHttpStatusCode(exception, out httpStatus))
            {
                return ProvisioningErrorHandling.IsTransientError(exception)
                    ? (IProvisioningEvent)new DiscoveryFailedTransientEvent(exception, httpStatus)
                    : new DiscoveryFailedPermanentEvent(exception, httpStatus);
            }

            return ProvisioningErrorHandling.IsTransientError(exception)
                ? (IProvisioningEvent)new DiscoveryFailedTransientEvent(exception)
                : new DiscoveryFailedPermanentEvent(exception);
        }
开发者ID:TeamKnowledge,项目名称:lokad-cloud-provisioning,代码行数:14,代码来源:AzureDiscovery.cs


示例10: Start

        public void Start()
        {
            m_InstanciedServiceList = new List<object>();
            var list = GetServiceTypeList();
            System.Diagnostics.Trace.WriteLine(string.Format("{0} services found", list.Count()));
            m_ServiceList = list.Where(i => !i.Item1).Select(i => Type.GetType(i.Item2)).ToList();
            var autoUpdateServiceHostList = list.Where(i => i.Item1).Select(i => i.Item2).ToList();

            var failList = new List<Exception>();
            StartServices(failList);
            if (failList.Count > 0)
            {
                var failStartException = new AggregateException("Start services failed", failList);
                throw failStartException;
            }
        }
开发者ID:chouteau,项目名称:palace,代码行数:16,代码来源:Starter.cs


示例11: GetMessageAndStackTrace

        public static String GetMessageAndStackTrace(AggregateException e)
        {
            if (e == null)
            {
                throw new ArgumentNullException("e", "AggregateException can not be null.");
            }

            var sb = new StringBuilder();

            foreach (Exception innerException in e.InnerExceptions)
            {
                sb.AppendLine(innerException.Message);
                sb.AppendLine("\t" + innerException.StackTrace);
            }

            return sb.ToString();
        }
开发者ID:gnikolaropoulos,项目名称:.Net-Labs,代码行数:17,代码来源:ExceptionServices.cs


示例12: ThrowAsync

        /// <summary>Throws the exception on the ThreadPool.</summary>
        /// <param name="exception">The exception to propagate.</param>
        /// <param name="targetContext">The target context on which to propagate the exception.  Null to use the ThreadPool.</param>
        internal static void ThrowAsync(Exception exception, SynchronizationContext targetContext)
        {
            // If the user supplied a SynchronizationContext...
            if (targetContext != null)
            {
                try
                {
                    // Post the throwing of the exception to that context, and return.
                    targetContext.Post(state => { throw PrepareExceptionForRethrow((Exception)state); }, exception);
                    return;
                }
                catch (Exception postException)
                {
                    // If something goes horribly wrong in the Post, we'll 
                    // propagate both exceptions on the ThreadPool
                    exception = new AggregateException(exception, postException);
                }
            }

            // Propagate the exception(s) on the ThreadPool
            ThreadPool.QueueUserWorkItem(state => { throw PrepareExceptionForRethrow((Exception)state); }, exception);
        }
开发者ID:Dmk1k,项目名称:referencesource,代码行数:25,代码来源:AsyncServices.cs


示例13: Exception

        public void Should_persist_and_unwrap_multiple_nested_original_exception_in_requestexecutionexception_with_exceptions_on_multiple_levels()
        {
            // Given
            var expectedException1 = new Exception();
            var expectedException2 = new Exception();
            var expectedException3 = new Exception();
            var expectedException4 = new Exception();
            var expectgedInnerExceptions = 4;
            var exceptionsListInner = new List<Exception>() { expectedException1, expectedException2, expectedException3 };
            var expectedExceptionInner = new AggregateException(exceptionsListInner);
            var exceptionsListOuter = new List<Exception>() { expectedExceptionInner, expectedException4 };
            var aggregateExceptionOuter = new AggregateException(exceptionsListOuter);

            var resolvedRoute = new ResolveResult(
               new FakeRoute(),
               DynamicDictionary.Empty,
               null,
               null,
               null);

            A.CallTo(() => resolver.Resolve(A<NancyContext>.Ignored)).Returns(resolvedRoute);

            A.CallTo(() => this.requestDispatcher.Dispatch(context, A<CancellationToken>._))
                .Returns(TaskHelpers.GetFaultedTask<Response>(aggregateExceptionOuter));

            var pipelines = new Pipelines();
            pipelines.OnError.AddItemToStartOfPipeline((ctx, exception) => null);
            engine.RequestPipelinesFactory = (ctx) => pipelines;

            var request = new Request("GET", "/", "http");

            // When
            var result = this.engine.HandleRequest(request);
            var returnedException = result.Items["ERROR_EXCEPTION"] as RequestExecutionException;

            // Then
            var returnedInnerException = returnedException.InnerException as AggregateException;
            returnedInnerException.ShouldBeOfType(typeof(AggregateException));
            Assert.Equal(expectgedInnerExceptions, returnedInnerException.InnerExceptions.Count);
        }
开发者ID:ravindrapro,项目名称:Nancy,代码行数:40,代码来源:NancyEngineFixture.cs


示例14: Should_persist_and_unwrap_original_exception_in_requestexecutionexception

        public void Should_persist_and_unwrap_original_exception_in_requestexecutionexception()
        {
            // Given
            var expectedException = new Exception();
            var aggregateException = new AggregateException(expectedException);

            var resolvedRoute = new ResolveResult(
               new FakeRoute(),
               DynamicDictionary.Empty,
               null,
               null,
               null);

            A.CallTo(() => resolver.Resolve(A<NancyContext>.Ignored)).Returns(resolvedRoute);

            A.CallTo(() => this.requestDispatcher.Dispatch(context, A<CancellationToken>._))
                .Returns(TaskHelpers.GetFaultedTask<Response>(aggregateException));

            var pipelines = new Pipelines();
            pipelines.OnError.AddItemToStartOfPipeline((ctx, exception) => null);
            engine.RequestPipelinesFactory = (ctx) => pipelines;

            var request = new Request("GET", "/", "http");

            // When
            var result = this.engine.HandleRequest(request);
            var returnedException = result.Items["ERROR_EXCEPTION"] as RequestExecutionException;

            // Then
            returnedException.InnerException.ShouldBeSameAs(expectedException);
        }
开发者ID:ravindrapro,项目名称:Nancy,代码行数:31,代码来源:NancyEngineFixture.cs


示例15: RealRun

        /// <summary>
        /// The method that performs the tests
        /// Depending on the inputs different test code paths will be exercised
        /// </summary>
        internal void RealRun()
        {
            TaskScheduler tm = TaskScheduler.Default;

            CreateTask(tm, _taskTree);
            // wait the whole task tree to be created 
            _countdownEvent.Wait();

            Stopwatch sw = Stopwatch.StartNew();

            try
            {
                switch (_api)
                {
                    case API.Cancel:
                        _taskTree.CancellationTokenSource.Cancel();
                        break;

                    case API.Wait:
                        switch (_waitBy)
                        {
                            case WaitBy.None:
                                _taskTree.Task.Wait();
                                _taskCompleted = true;
                                break;
                            case WaitBy.Millisecond:
                                _taskCompleted = _taskTree.Task.Wait(_waitTimeout);
                                break;
                            case WaitBy.TimeSpan:
                                _taskCompleted = _taskTree.Task.Wait(new TimeSpan(0, 0, 0, 0, _waitTimeout));
                                break;
                        }
                        break;
                }
            }
            catch (AggregateException exp)
            {
                _caughtException = exp.Flatten();
            }
            finally
            {
                sw.Stop();
            }

            if (_waitTimeout != -1)
            {
                long delta = sw.ElapsedMilliseconds - ((long)_waitTimeout + s_deltaTimeOut);

                if (delta > 0)
                {
                    Debug.WriteLine("ElapsedMilliseconds way more than requested Timeout.");
                    Debug.WriteLine("WaitTime= {0} ms, ElapsedTime= {1} ms, Allowed Descrepancy = {2} ms", _waitTimeout, sw.ElapsedMilliseconds, s_deltaTimeOut);
                    Debug.WriteLine("Delta= {0} ms", delta);
                }
                else
                {
                    var delaytask = Task.Delay((int)Math.Abs(delta));  // give delay to allow Context being collected before verification
                    delaytask.Wait();
                }
            }

            Verify();
            _countdownEvent.Dispose();
        }
开发者ID:ChuangYang,项目名称:corefx,代码行数:68,代码来源:TaskCancelWaitTest.cs


示例16: TestWorkCancelledException

        public void TestWorkCancelledException()
        {
            // prepare workAction to throw exception
            Exception currentException = null;
            Func<Task> workAction = () => { throw currentException; };

            // initialize worker
            using (var worker = new MockWorker(workAction))
            {
                var finishedEvent = new AutoResetEvent(false);
                worker.OnWorkFinished += () => { finishedEvent.Set(); };

                bool wasError;
                worker.OnWorkError += e => wasError = true;

                // start worker
                worker.Start();

                // throw OperationCanceledException
                wasError = false;
                currentException = new OperationCanceledException();
                worker.NotifyWork();

                // verify work finished
                Assert.IsTrue(finishedEvent.WaitOne(1000));
                Assert.IsFalse(wasError);

                // throw Exception
                wasError = false;
                currentException = new Exception();
                worker.NotifyWork();

                // verify work errored
                Assert.IsTrue(finishedEvent.WaitOne());
                Assert.IsTrue(wasError);

                // throw AggregateException of all OperationCanceledException
                wasError = false;
                currentException = new AggregateException(new OperationCanceledException(), new OperationCanceledException());
                worker.NotifyWork();

                // verify work finished
                Assert.IsTrue(finishedEvent.WaitOne());
                Assert.IsFalse(wasError);

                // throw AggregateException of some OperationCanceledException
                wasError = false;
                currentException = new AggregateException(new OperationCanceledException(), new Exception());
                worker.NotifyWork();

                // verify work errored
                Assert.IsTrue(finishedEvent.WaitOne());
                Assert.IsTrue(wasError);
            }
        }
开发者ID:ArsenShnurkov,项目名称:BitSharp,代码行数:55,代码来源:WorkerTest.cs


示例17: FireUnobservedEvent

		internal UnobservedTaskExceptionEventArgs FireUnobservedEvent (AggregateException e)
		{
			UnobservedTaskExceptionEventArgs args = new UnobservedTaskExceptionEventArgs (e);
			
			EventHandler<UnobservedTaskExceptionEventArgs> temp = UnobservedTaskException;
			if (temp == null)
				return args;
			
			temp (this, args);
			
			return args;
		}
开发者ID:metanest,项目名称:mono,代码行数:12,代码来源:TaskScheduler.cs


示例18: AddException

 public static void AddException(ref AggregateException target, Exception source)
 {
     target = ReferenceEquals(target, null) ? new AggregateException(source) : (new AggregateException(source, target)).Flatten();
 }
开发者ID:mesheets,项目名称:Theraot-CF,代码行数:4,代码来源:AggregateExceptionHelper.cs


示例19: OnDisconnectError

 private static void OnDisconnectError(AggregateException ex, object state)
 {
     ((TraceSource)state).TraceEvent(TraceEventType.Error, 0, "Failed to raise disconnect: " + ex.GetBaseException());
 }
开发者ID:Choulla-Naresh8264,项目名称:SignalR,代码行数:4,代码来源:TransportDisconnectBase.cs


示例20: UploadFileToBlob


//.........这里部分代码省略.........
                                fs.Seek(blockIdAndLength.Key * (long)maxBlockSize, SeekOrigin.Begin);
                                int readSize = binaryReader.Read(buffer, 0, blockIdAndLength.Value);

                                if (fileEncryption != null)
                                {
                                    lock (fileEncryption)
                                    {
                                        using (FileEncryptionTransform encryptor = fileEncryption.GetTransform(file.Name, blockIdAndLength.Key * (long)maxBlockSize))
                                        {
                                            encryptor.TransformBlock(buffer, 0, readSize, buffer, 0);
                                        }
                                    }
                                }

                                using (var ms = new MemoryStream(buffer, 0, blockIdAndLength.Value))
                                {
                                    string blockIdString = Convert.ToBase64String(Encoding.ASCII.GetBytes(string.Format(CultureInfo.InvariantCulture, "BlockId{0}", blockIdAndLength.Key.ToString("0000000", CultureInfo.InvariantCulture))));
                                    string blockHash = GetMd5HashFromStream(buffer);
                                    if (blob != null) blob.PutBlock(blockIdString, ms, blockHash, options: options);
                                }

                                Interlocked.Add(ref bytesSent, blockIdAndLength.Value);
                                var progress = (int)((double)bytesSent / file.Length * 100);
                                var eArgs = new BlobTransferProgressChangedEventArgs(bytesSent, blockIdAndLength.Value, file.Length, progress, _uploadSpeedCalculator.UpdateCountersAndCalculateSpeed(bytesSent), uri, localFile, null);
                                OnTaskProgressChanged(eArgs);
                            }
                            catch (StorageException ex)
                            {
                                TimeSpan tm;
                                exceptionCount++;
                                exceptions.Add(ex);
                                if (!retryPolicy.ShouldRetry(exceptions.Count, ex.RequestInformation.HttpStatusCode, ex, out tm, new OperationContext()))
                                {
                                    lastException = new AggregateException(String.Format(CultureInfo.InvariantCulture, "Received {0} exceptions while uploading. Canceling upload.", exceptions.Count), exceptions);
                                    throw lastException;
                                }
                                Thread.Sleep(tm);

                                queue.Enqueue(blockIdAndLength);
                            }
                            catch (IOException ex)
                            {
                                TimeSpan tm;
                                exceptionCount++;
                                exceptions.Add(ex);
                                if (!retryPolicy.ShouldRetry(exceptions.Count, 0, ex, out tm, new OperationContext()))
                                {
                                    lastException = new AggregateException(String.Format(CultureInfo.InvariantCulture, "Received {0} exceptions while reading file {1} @ location {2} to be uploaded. Canceling upload.",
                                        exceptions.Count, file.Name, blockIdAndLength.Key * (long)maxBlockSize), exceptions);
                                    throw lastException;
                                }

                                // dispose existing file stream
                                if (fs != null)
                                {
                                    fs.Close();
                                }

                                Thread.Sleep(tm);

                                // try to reopen the file stream again
                                fs = new FileStream(file.FullName, FileMode.Open, FileAccess.Read);
                                queue.Enqueue(blockIdAndLength);
                            }
                        }
                    }
开发者ID:votrongdao,项目名称:azure-sdk-for-media-services,代码行数:67,代码来源:BlobTransferClient.cs



注:本文中的AggregateException类示例整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
C# AggregateType类代码示例发布时间:2022-05-24
下一篇:
C# AggregateClause类代码示例发布时间:2022-05-24
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap