Continue the task on the main topic

I know there is a similar question: Continue with the task in the main thread

but this question is more related to wpf, and I don’t see it working on a console application.

I want to execute a method on another thread, and when this method is completed, I want to continue execution on the main thread. I do not want to join the method. anyway here is what i have:

class Program
{
    static void Main(string[] args)
    {
        Thread.CurrentThread.Name = "MAIN";

        DoWork(x =>
        {
            Console.Write("Method successfully executed. Executing callback method in thread:" +
                "\n" + Thread.CurrentThread.Name);
        });

        Console.Read();
    }

    static void DoWork(Action<bool> onCompleteCallback)
    {
        Console.Write(Thread.CurrentThread.Name); // show on what thred we are executing

        Task doWork = new Task(() =>
        {
            Console.Write(Thread.CurrentThread.Name); // show on what thred we are executing
            Thread.Sleep(4000);
        });

        Action<Task> onComplete = (task) =>
        {                
            onCompleteCallback(true);
        };

        doWork.Start(); 

        // this line gives an error!
        doWork.ContinueWith(onComplete, TaskScheduler.FromCurrentSynchronizationContext());                       
    }
}

How can I execute the onCompleteCallback method in the main thread?

+5
source share
1 answer

but this question is more related to wpf, and I don’t see it working on a console application.

( ) . , TPL , , SynchronizationContext. (.. Application.Run Windows Forms WPF ..).

, , , . "" - , .

, , , , , , .


"" . , :

class Program
{
    static void Main(string[] args)
    {
        Thread.CurrentThread.Name = "MAIN";

        Task workTask = DoWork();

        workTask.Wait(); // Just wait, and the thread will continue
                         //  when the work is complete

        Console.Write("Method successfully executed. Executing callback method in thread:" +
                "\n" + Thread.CurrentThread.Name);
        Console.Read();
    }

    static Task DoWork()
    {
        Console.Write(Thread.CurrentThread.Name); // show on what thred we are executing

        Task doWork = new Task(() =>
        {
            Console.Write(Thread.CurrentThread.Name); // show on what thred we are executing
            Thread.Sleep(4000);
        });

        doWork.Start(); 

        return doWork;
    }
}
+6

All Articles