【问题标题】:Getting a Task's unexpected Exception to bring down the application earlier than Garbage Collection获取任务的意外异常以在垃圾收集之前关闭应用程序
【发布时间】:2013-05-13 00:48:04
【问题描述】:

通常,对于我不希望抛出异常但会抛出异常的代码(即编程错误),我希望我的应用程序崩溃(这样它就不会损坏数据、向用户报告无效数据等)。 )。

在使用Tasks 时,是否有获得(接近)这种行为的最佳实践?我们已经为TaskScheduler.UnobservedTaskException 注册了一个处理程序。问题在于,这可能比导致意外异常的时间晚很多

问题: 如果有的话我应该使用哪个选项:

  1. 我是否应该将我的 Tasks 操作包装在 try/catch 中,并在 catch 中升级我不期望的异常?如果是这样,我应该怎么做才能升级(即我想让它触发 AppDomain.UnhandledException 事件并终止。

  2. 我是否应该在 ui 线程(这是一个 Winforms 应用程序)上附加一个延续 (OnlyOnFaulted),如果它不是预期的异常,它会重新引发异常?

  3. 有更好或更标准的方法吗?

这是 #1 的样子:

var t1 = Task.Factory.StartNew(() =>
    {
        try
        {
            string path = null; // Programming error.  Should have been a valid string.  Will cause System.ArgumentNullException below
            using (FileStream fs = File.Create(path))
            {

            }
        }
        catch (System.IO.IOException) { throw; } // Expected possible exception
        catch (System.UnauthorizedAccessException) { throw; }
        catch
        {
            // Anything caught here is not an expected exception and should be escalated.
            // But how?
        }
    });

下面是#2 的样子:

TaskScheduler uiTaskScheduler = TaskScheduler.FromCurrentSynchronizationContext();
var t1 = Task.Factory.StartNew(() =>
    {
        string path = null; // Programming error.  Should have been a valid string.  Will cause System.ArgumentNullException below
        using (FileStream fs = File.Create(path))
        {

        }
    });

t1.ContinueWith(t =>
    {
        Exception ex = t.Exception;
        if (ex is IOException || ex is UnauthorizedAccessException) // Expected exceptions (do nothing)
            return;

        throw ex; // Not expected (escalate by rethrowing)

    }, CancellationToken.None, TaskContinuationOptions.OnlyOnFaulted, uiTaskScheduler);

【问题讨论】:

    标签: c# exception-handling task-parallel-library


    【解决方案1】:

    附加一个延续对我来说是一个很好的方法。如果您对不会因为其他原因阻塞 UI 线程太久的假设感到满意,那么强制继续在 UI 线程上运行对我来说似乎是一个非常合理的选择。这样,您也可以执行任何您需要的 UI 任务,作为紧急关机的一部分。

    【讨论】:

      猜你喜欢
      • 2014-10-17
      • 1970-01-01
      • 2012-01-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-04-21
      • 2011-01-18
      • 1970-01-01
      相关资源
      最近更新 更多