简体   繁体   English

使用任务和异常处理进行多线程处理

[英]Multithreading with Tasks and exception handling

I have an application created in C# .Net 4.5. 我有一个用C#.Net 4.5创建的应用程序。 I am using multithreading via the task class. 我通过任务类使用多线程。 I want to add some error handling. 我想添加一些错误处理。 Specifically I want any exception to bubble up to the top of my application. 具体来说,我希望任何例外都可以冒泡到我的应用程序的顶部。

Where I am stuck is how unhandled exceptions or any for that matter work whilst using tasks. 我遇到的问题是在使用任务时,未处理的异常或任何与此有关的异常。

I have been reading this page http://msdn.microsoft.com/en-us/library/dd997415(v=vs.110).aspx . 我一直在阅读此页面http://msdn.microsoft.com/en-us/library/dd997415(v=vs.110).aspx My understanding is that if I have multiple tasks running and error happens that I have to wait until the Task.WaitAll(someTask) is called and can handle it there - is that correct? 我的理解是,如果我有多个任务正在运行并且发生错误,我必须等到调用Task.WaitAll(someTask)并且可以在那里处理它 - 这是正确的吗? Is it possible when an error happens on one task to cancel all the other tasks before having to wait for Task.WaitAll(someTask)? 是否有可能在一个任务上发生错误,在必须等待Task.WaitAll(someTask)之前取消所有其他任务?

Below is a snippet of my code. 下面是我的代码片段。 I guess with nested tasks the same principle applies that I would have to wait until after both Task.WAitAll()'s have been called before handling my error? 我想嵌套任务同样的原则适用于我必须等到在处理我的错误之前调用了Task.WAitAll()之后? My approach for this application is rather simple, any execption thrown I want to be logged and then close the application. 我对这个应用程序的方法相当简单,我想要记录任何execption,然后关闭应用程序。 Just not sure how this works with tasks. 只是不确定这如何适用于任务。

Also is it correct the way I am creating two TaskFactory's? 它是否正确我创建两个TaskFactory的方式? Both methods are in different classes. 两种方法都在不同的类中。

public void RunTimePeriods()
        {
            _taskFactory = new TaskFactory();

            Task[] taskTimePeriod = new Task[_timePeriods.Length];

            for (int i = 0; i < taskTimePeriod.Length; i++)
                taskTimePeriod[i] = _taskFactory.StartNew(_timePeriods[i].RunIndicators);

            Task.WaitAll(taskTimePeriod);
         }


public void RunIndicators()
        {
            _taskFactory = new TaskFactory();

            Task[] taskIndicator = new Task[_indicator.Length];

            for (int i = 0; i < taskIndicator.Length; i++)
                taskIndicator[i] = _taskFactory.StartNew(_indicator[i].Run);
        }

Is it possible when an error happens on one task to cancel all the other tasks before having to wait for Task.WaitAll(someTask)? 是否有可能在一个任务上发生错误,在必须等待Task.WaitAll(someTask)之前取消所有其他任务?

The only way you can do this is to notify the other tasks to stop what they are doing. 您可以这样做的唯一方法是通知其他任务停止他们正在做的事情。 The general solution for this type of communication is to use task cancellation . 此类通信的一般解决方案是使用任务取消

Here's a good walkthrough . 这是一个很好的演练

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM