What is the difference between Task.Run and Task.Factory.StartNew

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;
}
+4
source share
1 answer

Task.Run , Task.Factory.StartNew, . . Run:

Task.Run(someAction);

:

Task.Factory.StartNew(someAction, 
    CancellationToken.None, TaskCreationOptions.DenyChildAttach, TaskScheduler.Default);

.

CancellationToken.None, TaskCreationOptions.DenyChildAttach TaskScheduler.Default Task.Factory.StartNew, .

+4

Source: https://habr.com/ru/post/1660776/


All Articles