I guess I'm not really understanding the await command in c#. I thought that using await would allow a method to continue processing and would would work in a separate thread and return a value once it completed however, I have the following code:
public async Task<DatabaseActionResult> BackupToAzureAsync(DatabaseSchedule schedule)
{
try
{
foreach (var o in myObjects)
{
await new Task(async () =>
{
try
{
//Do some stuff.
}
catch (Exception e)
{
throw; //Should this throw the exception to the functions Try/Catch block so it can log it to the event viewer?
}
}
}
}
catch (Exception e)
{
//Log exception to event viewer and return a DatabaseActionResult object
}
}
However, the foreach() executes, waits for the task to complete, and then only after completion, continues to the next. If I remove the await statement, then it runs the task for every loop iteration simultaneously but the Try/Catch block doesn't throw the exception up the stack. Instead it just stop the service entirely as if it were a service unhandled exception.
How can I either get the new task to run once for each for/each loop without waiting for the previous one to complete, or how can I get the try/catch block to throw the exception up the stack so it can get caught and processed in the method's try/catch block?
Thanks!
FOLLOW-UP:
Would this work and still maintain the Try/Catch stack?
foreach (var t in tables)
{
try
{
var tableTasks = new List<Task>
{
new Task(async () =>
{
try
{
//Do stuff
}
catch (DataError e)
{
throw e;
}
catch (Exception e)
{
throw e;
}
}
)
};
}
catch (Exception e)
{
return new DatabaseActionResult();
}
}