2
await/async에 대한 이해를 돕기 위해 테스트 응용 프로그램을 작성했습니다. 나는 잘 작동하는 MethodAsync1()
방법이 있습니다. 그러나 Main()에서 호출하면 MethodAsync1()이 완료 될 때까지 기다리는 방법을 알 수 없습니다. 아래 코드를 참조하십시오.메인 내에서 기다리는 방법
class Program
{
static void Main(string[] args)
{
Debug.WriteLine(DateTime.Now + " Main()1");
Task<String> v1 = MethodAsync1();
Debug.WriteLine(DateTime.Now + " Main()2 - prints out before Method1 finishes");
// I now want to wait for MethosAsync1() to complete before I go further.
// This line has error:
// Error 1 The 'await' operator can only be used within an async
// method. Consider marking this method with the 'async' modifier and
// changing its return type to 'Task'.
String v2 = await v1;
Debug.WriteLine(DateTime.Now + " Main()3 - Method1() now finished");
}
static async Task<String> MethodAsync1()
{
Debug.WriteLine(DateTime.Now + " Method1()1 ");
HttpClient client = new HttpClient();
Task<HttpResponseMessage> responseTask = client.GetAsync("http://bbc.co.uk");
// Do other stuff
Debug.WriteLine(DateTime.Now + " Method1()2 ");
// Wait for it to finish - yield thread back to Main()
var response= await responseTask;
// responseTask has completed - so thread goes back here and method returns fully
Debug.WriteLine(DateTime.Now + " Method1()3 ");
return "finished";
}
}
'main'도'async' 메소드로 만들 수 있습니까? – StriplingWarrior
아니요. 'await1.Program.Main (string [])': 진입 점에 'async'수정자를 사용할 수 없습니다. ' – spiderplant0
왜'main'이 비동기입니까? 그건 말이 안돼. 결과를 얻을 때까지 스레드를 차단하십시오. – poke