It seems that tasks start automatically

I am porting a program that had a very long download time, which was not improved at all when I ported it, because slowness was associated with access to the db server (and not to the non-optimal code). I moved the download to a separate thread using the library Tasks, and now the user interface does not freeze at boot, but I was interested to know something:

The object Task.Factoryhas a method StartNewthat should create a new task, start it and return a link to it. This makes sense, but it seems like the constructor is Taskdoing the same.

When I do the following:

Task catsFromDB = new Task(() => AddCategoriesFromDB(cts.Token), cts.Token);
catsFromDB.Start();

I am getting an error InvalidOperationExceptionthat I really don't understand. Looks like I already threw him away. Which I don’t have.

[EDIT]

. erorr: "InvalidOperationException," Start "cannot be called for a task that completed"

[EDIT]

The error is the cancellation code that I included. I needed to reset cancel before trying to start it again.

+3
source share
3 answers

Now I feel stupid, but instructive to let others learn from my "green" (as in the "new", "inexperienced") error:

I need the operation in question to be canceled and restarted, so I performed the "CancelLoad" operation, which always started before the actual boot. It turns out I forgot to create a new token after cancellation and waiting.

+5
source

. Start.

using System;
using System.Threading;
using System.Threading.Tasks;

class Test
{
    static void Main()
    {
        var cts = new CancellationTokenSource();
        Console.WriteLine("Creating task...");
        Task task = new Task(() => Console.WriteLine("Task executing"),
                             cts.Token);
        Console.WriteLine("Sleeping...");
        Thread.Sleep(1000);
        Console.WriteLine("Starting task...");
        task.Start();
        Thread.Sleep(1000);
    }
}

, - , . , , , .

+1

: , AddCategoriesFromDB(cts.Token), . , , , . ?

0

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


All Articles