简体   繁体   English

C#中任务的异常处理

[英]Exception handling in tasks in c#

I have problems with exception handling in tasks. 我在任务中有异常处理问题。 I've found on MSDN the page to exception handling in tasks, but the example doesn't work for me... 我在MSDN上找到了任务中异常处理的页面,但是该示例对我不起作用...

I would expect, that the exception should be handled, but if I start the program, I get an unhandled exception error. 我希望应该处理该异常,但是如果我启动程序,则会收到未处理的异常错误。

Thanks. 谢谢。

https://msdn.microsoft.com/en-us/library/dd537614%28v=vs.110%29.aspx https://msdn.microsoft.com/zh-CN/library/dd537614%28v=vs.110%29.aspx

   using System;
   using System.Collections.Generic;
   using System.Linq;
   using System.Text;
   using System.Threading.Tasks;

   namespace TaskExceptionTest
   {

class Program
{
    static string[] GetAllFiles(string str)
    {
        // Should throw an AccessDenied exception on Vista. 
        return System.IO.Directory.GetFiles(str, "*.txt", System.IO.SearchOption.AllDirectories);
    }
    static void HandleExceptions()
    {
        // Assume this is a user-entered string. 
        string path = @"C:\";

        // Use this line to throw UnauthorizedAccessException, which we handle.
        Task<string[]> task1 = Task<string[]>.Factory.StartNew(() => GetAllFiles(path));

        // Use this line to throw an exception that is not handled. 
        //Task task1 = Task.Factory.StartNew(() => { throw new IndexOutOfRangeException(); } ); 
        try
        {
            task1.Wait();
        }
        catch (AggregateException ae)
        {

            ae.Handle((x) =>
            {
                if (x is UnauthorizedAccessException) // This we know how to handle.
                {
                    Console.WriteLine("You do not have permission to access all folders in this path.");
                    Console.WriteLine("See your network administrator or try another path.");
                    return true;
                }
                return false; // Let anything else stop the application.
            });

        }

        Console.WriteLine("task1 has completed.");
    }

    static void Main(string[] args)
    {
        HandleExceptions();
    }
}

} }

Returning false is rethrowing the Exception. 返回false将抛出异常。 If you just want to print the extra error information, then replace the return false with return true and get rid of the return in the if block. 如果你只是想打印的额外的错误信息,然后更换return falsereturn true ,并摆脱了returnif块。

ae.Handle((x) =>
        {
            if (x is UnauthorizedAccessException) // This we know how to handle.
            {
                Console.WriteLine("You do not have permission to access all folders in this path.");
                Console.WriteLine("See your network administrator or try another path.");
            }
            return true; 
        });

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

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