P
P
Peter2018-08-23 15:49:59
C++ / C#
Peter, 2018-08-23 15:49:59

How to properly delay Task?

Good afternoon. In a console application, it is required to implement a very simple timer that would call the desired method in another thread in a second and the result of the method would be displayed on the console.
I tried to do it like this.

class Program
    {
        static void Main(string[] args)
        {
            Test t = new Test();

            Console.WriteLine("Before task");

            Task.Run(() =>
            {
                while (true)
                {
                    Console.WriteLine(t.GetTime());
                    Task.Delay(1000);
                }
            });

            Console.WriteLine("After task");

            Console.ReadKey();
        }
    }

    public class Test
    {
        public string GetTime()
        {
            return DateTime.Now.ToLongTimeString();
        }
    }

I get this picture.
spoiler
5b7eacc62e047408031660.png

It is worth changing Task.Delay to Thread.Sleep, then I get the result I need.
spoiler
5b7ead3e2fbf5174031422.png

How to correctly interrupt Task and achieve the desired result. Thanks in advance for your replies.

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question