R
R
rFczZZ2016-06-13 21:07:34
Angular
rFczZZ, 2016-06-13 21:07:34

Why does an async method run as a separate thread?

Good afternoon. I'm trying to understand how async/await work. In the code below: two loops, one draws a number on the first line of the console window, the second - on the second. Since the ShowMessage function saves and restores state, it should not conflict with itself from wherever it is called "synchronously" (which I believe the async/await mechanism should do, i.e. it should interrupt the main thread wherever it is called). was and call this function in this thread, then return control back). But by running the application, you can see that the text is displayed anywhere, as it would be with a thread conflict.
Tell me what am I doing wrong?

public static void Main()
{
    DrawCounter();
    while(true) ShowMessage(DateTime.Now);              // A
}

public static async void DrawCounter()
{
    int counter = 0;
    while(true)                                         // B
    {
        ShowMessage(counter++, 0, 1, ConsoleColor.Red);
        await Task.Delay(1);                            // C
    }
}

public static void ShowMessage(object Message, int Left = 0, int Top = 0, 
    ConsoleColor Color = ConsoleColor.Gray)
{
    int oldLeft = Console.CursorLeft;
    int oldTop = Console.CursorTop;
    var oldColor = Console.ForegroundColor;

    Console.ForegroundColor = Color;
    Console.SetCursorPosition(Left, Top);
    Console.Write(Message);

    Console.CursorLeft = oldLeft;
    Console.CursorTop = oldTop;
    Console.ForegroundColor = oldColor;
}

Answer the question

In order to leave comments, you need to log in

2 answer(s)
G
GaserV, 2015-10-25
@GaserV

It turns out a trace. situation. I have ng-routes connected. In addition, laravel is installed. In the routes, laravel prescribed that when "/newrecord" is requested, a function in the controller will be triggered, which is responsible for adding an article\news. But the bottom line is that how do I correctly write the URL on angular in $http? I either have a 500th error, or 405. In this case, an array of data from the form is transmitted. How to edit?

#
#algooptimize #bottize, 2016-06-13
@rFczZZ

1. The thread is not interrupted.
2 DrawCounter();
you should most likely do
DrawCounter().Wait()
or
await DrawCounter();
Otherwise, after the first await inside DrawCounter
, the control gets right here while(true) ShowMessage(DateTime.Now);
3. The context matters, in the gui thread by default, at the end of a new task after await, control is transferred back to the gui thread, this will not happen here.
Then I recommend to google and read more. Too lazy to type a lot.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question