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.
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
'development' 카테고리의 다른 글
문자열 "true"/ "false"를 부울 값으로 변환 (0) | 2020.05.27 |
---|---|
EditText 깜박임 커서 비활성화 (0) | 2020.05.27 |
Mac에서 Android SDK 찾기 및 PATH 추가 (0) | 2020.05.27 |
XCTest의 기본 모듈을로드 할 수 없습니다 (0) | 2020.05.27 |
레일에서 네임 스페이스 내에 컨트롤러를 생성하는 방법 (0) | 2020.05.27 |