Task planning and task creation

I am pretty confused about this issue. I proceed from the assumption that the task creation and its planning should be strictly separated, and the seams should not be in C #.

Consider the following simple code.

        static async Task simpleton()
        {
            print("simpleton");
        }

        static async Task cont()
        {
            print("cont");
        }

        static void Main(string[] args)
        {
            Task t1 = simpleton();

            Task t2 = t1.ContinueWith((a) => { cont(); });

            Thread.Sleep(1000);

            return;
        }

Output signal

simpleton
cont

the simpleton function starts and creates the task t1 (already completed) - this is normal. Nevertheless, t2-seams should be (at least in the code) only a task creation - planning was not requested from the system, so why and who plans to continue to run? Obviously, the creation / launch principle is violated here.

. . , , . , : -

static async Task foo()
        {
            await bar();
        }

        static async Task bar()
        {
            print("bar");
        }

        static void Main(string[] args)
        {
            foo();

            Thread.Sleep(1000);
            return;
        }

bar Task, foo.

, :

  • , ContinueWith , .

  • , , , , , ( SynchronizationContext TaskScheduler).

  • ( ) / ?

+4
3

TaskScheduler ContinueWith. , . , .

SynchronizationContext TaskScheduler . , , async . ( , ).

async .

, ContinueWith , .

, .

, , , , ( SynchronizationContext TaskScheduler).

, ( ) .

( ) / ?

/ . . , . , -, . .

Task.Start (TaskScheduler).

. , . TaskScheduler . .

, awaiter. , await Task.Factory.StartNew(..., myScheduler).

bar Task, foo.

. . , TaskCompletionSource. .

+4

, ContinueWith , .

ContinueWith Task TaskScheduler . no TaskScheduler , TaskScheduler.Current .

, , , , ( SynchronizationContext TaskScheduler).

await Task. await , Task. await, , SynchronizationContext. ( ConfigureAwait(false)), .

( ) / ?

await , . Task.Run Task.Factory.Startnew Task , ContinueWith, .

+1

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


All Articles