I know that this question was asked before, but I did not get the right answer after searching on Google.
I have these lines of code:
Task.Run(() => DoSomething())
.ContinueWith(t=>Log.Error(t,"Error"), TaskContinuationOptions.OnlyOnFaulted);
Task.Factory.StartNew(() => DoSomething())
.ContinueWith(t=>Log.Error(t,"Error"),TaskContinuationOptions.OnlyOnFaulted);
After successful execution DoSomething, Task.Runthrows TaskCanceledExceptionis still Task.Factory.StartNewworking fine. Why?
next reading:
Stephen Clear why not use Task.Factory.StartNew
MSDN Link
UPDATE 2:
Code Example:
private async void button27_Click(object sender, EventArgs e)
{
var r = new Random(System.DateTime.Now.Millisecond);
await Task.Factory.StartNew(
() => {
Divide(r.Next(100), r.Next(-1, 10));
Log.Information("Divide Done!");
},
CancellationToken.None,
TaskCreationOptions.DenyChildAttach,
TaskScheduler.Default)
.ContinueWith(
t => {
Log.Error(t.Exception,"There is an exception on Divide");
},
TaskContinuationOptions.OnlyOnFaulted);
}
private static void Divide(int a, int b)
{
var c = a/b;
}
Milad source
share