Catching an exception thrown in an asynchronous callback

后端 未结 3 614
日久生厌
日久生厌 2021-01-04 23:10

I have a method that takes a callback argument to execute asynchronously, but the catch block doesn\'t seem to be catching any exceptions thrown by the synchronous call (

3条回答
  •  日久生厌
    2021-01-04 23:32

    If you're targeting .NET 4.0, you can utilize the new Task Parallel Library, and observe the Task object's Exception property.

    public Task Submit(FileInfo file)
    {
        return Task.Factory.StartNew(() => DoSomething(file));
    }
    
    private void DoSomething(FileInfo file)
    {
        throw new Exception();
    }
    

    Then use it like this:

    Submit(myFileInfo).ContinueWith(task =>
    {
        // Check task.Exception for any exceptions.
    
        // Do stuff with task.Result
    });
    

    where DoSomething is the method you'd like call asynchronously, and the delegate you pass to ContinueWith is your callback.

    More information about exception handling in TPL can be found here: http://msdn.microsoft.com/en-us/library/dd997415.aspx

提交回复
热议问题