development

C #의 콘솔 앱에서 비동기?

big-blog 2020. 5. 27. 08:12
반응형

C #의 콘솔 앱에서 비동기? [복제]


이 질문에는 이미 답변이 있습니다.

이 간단한 코드가 있습니다.

public static async Task<int> SumTwoOperationsAsync()
{
    var firstTask = GetOperationOneAsync();
    var secondTask = GetOperationTwoAsync();
    return await firstTask + await secondTask;
}


private async Task<int> GetOperationOneAsync()
{
    await Task.Delay(500); // Just to simulate an operation taking time
    return 10;
}

private async Task<int> GetOperationTwoAsync()
{
    await Task.Delay(100); // Just to simulate an operation taking time
    return 5;
}

큰. 이것은 컴파일됩니다.

그러나 콘솔 응용 프로그램이 있고 위의 코드를 실행하고 싶다고합니다 (호출 SumTwoOperationsAsync())

 static  void Main(string[] args)
        {
             SumTwoOperationsAsync();
        }

그러나 나는 (사용하는 경우 읽었습니다 sync) 내가 곧 길이 모두를 동기화해야 까지 하고 아래로 :

질문 : 이것은 내 Main기능이로 표시되어야 함을 의미 async합니까?

그럼 그것은 할 수없는 컴파일 오류가 있기 때문에 수 :

진입 점에 '비동기'수정 자로 표시 할 수 없습니다.

async stuff를 이해하면 스레드가 Main함수로 들어가고 ----> SumTwoOperationsAsync----> 두 함수를 호출하고 꺼집니다. 하지만 ~까지SumTwoOperationsAsync

내가 무엇을 놓치고 있습니까?


대부분의 프로젝트 유형에서 async"위로"및 "아래로"는 async void이벤트 처리기 에서 끝나 거나 a Task를 프레임 워크 로 반환합니다 .

그러나 콘솔 앱은이를 지원하지 않습니다.

Wait반환 된 작업을 수행 할 수 있습니다 .

static void Main()
{
  MainAsync().Wait();
  // or, if you want to avoid exceptions being wrapped into AggregateException:
  //  MainAsync().GetAwaiter().GetResult();
}

static async Task MainAsync()
{
  ...
}

또는 내가 쓴 것과 같은 자신의 컨텍스트를 사용할있습니다 .

static void Main()
{
  AsyncContext.Run(() => MainAsync());
}

static async Task MainAsync()
{
  ...
}

async콘솔 앱에 대한 자세한 내용 내 블로그에 있습니다.


가장 간단한 방법은 다음과 같습니다.

static void Main(string[] args)
{
    Task t = MainAsync(args);
    t.Wait();
}

static async Task MainAsync(string[] args)
{
    await ...
}

빠르고 광범위한 솔루션으로 :

작업 결과

Both Task.Result and Task.Wait won't allow to improving scalability when used with I/O, as they will cause the calling thread to stay blocked waiting for the I/O to end.

When you call .Result on an incomplete Task, the thread executing the method has to sit and wait for the task to complete, which blocks the thread from doing any other useful work in the meantime. This negates the benefit of the asynchronous nature of the task.

notasync


My solution. The JSONServer is a class I wrote for running an HttpListener server in a console window.

class Program
{
    public static JSONServer srv = null;

    static void Main(string[] args)
    {
        Console.WriteLine("NLPS Core Server");

        srv = new JSONServer(100);
        srv.Start();

        InputLoopProcessor();

        while(srv.IsRunning)
        {
            Thread.Sleep(250);
        }

    }

    private static async Task InputLoopProcessor()
    {
        string line = "";

        Console.WriteLine("Core NLPS Server: Started on port 8080. " + DateTime.Now);

        while(line != "quit")
        {
            Console.Write(": ");
            line = Console.ReadLine().ToLower();
            Console.WriteLine(line);

            if(line == "?" || line == "help")
            {
                Console.WriteLine("Core NLPS Server Help");
                Console.WriteLine("    ? or help: Show this help.");
                Console.WriteLine("    quit: Stop the server.");
            }
        }
        srv.Stop();
        Console.WriteLine("Core Processor done at " + DateTime.Now);

    }
}

참고URL : https://stackoverflow.com/questions/17630506/async-at-console-app-in-c

반응형