How to handle Task.Run Exception

后端 未结 7 1065
离开以前
离开以前 2020-12-08 06:12

I had a problem with catching the exception from Task.Run which was resolved by changing the code as follows. I\'d like to know the difference between handling

7条回答
  •  无人及你
    2020-12-08 06:38

    In your Outside code you only check whether starting a task does not throw exception not task's body itself. It runs asynchronously and the code which initiated it is done then.

    You can use:

    void Outside()
    {
        try
        {
            Task.Run(() =>
            {
                int z = 0;
                int x = 1 / z;
            }).GetAwaiter().GetResult();
        }
        catch (Exception exception)
        {
            MessageBox.Show("Outside : " + exception.Message);
        }
    }
    

    Using .GetAwaiter().GetResult() waits until task ends and passes thrown exception as they are and does not wrap them in AggregateException.

提交回复
热议问题