-1

I have a task like:

var migrateTask = Task.Run(() =>
    {
        //do stuff
     });

migrateTask.ConfigureAwait(true).GetAwaiter().OnCompleted(this.MigrationProcessCompleted);

How to tell in the method MigrationProcessCompleted if I got an exception or task was faulted in the initial thread (in do stuff code block)?

Is there a way to find this without making the task a class member/property?

Buda Gavril
  • 21,409
  • 40
  • 127
  • 196

1 Answers1

2

You should never be really calling .GetAwaiter() it is intended for compiler use.

If you can use await your code is as simple as

public async Task YourFunc()
{

    Exception error = null
    try
    {
        await Task.Run(() =>
        {
            //do stuff
         });
    }
    catch(Exception ex)
    {
        error = ex;
    }

    MigrationProcessCompleted(error)
}

private void MigrationProcessCompleted(Exception error)
{
     //Check to see if error == null. If it is no error happend, if not deal withthe error.
}
Scott Chamberlain
  • 124,994
  • 33
  • 282
  • 431
  • In this case, in the code inside the run block throws an exception, will it be caught in the catch block? Because I've heard that the exception is not thrown when it occurs... – Buda Gavril Oct 27 '16 at 17:12
  • the `await` causes it to get caught by the catch block. if you had done `Task.Run` with no `await` then you would be correct. – Scott Chamberlain Oct 27 '16 at 18:29