[英]How can I wait for the asynchronous method result before execute the rest of the main thread?
[英]How wait asynchronous method in a thread?
我需要在Download.file方法完成后調用Join方法。 我試圖添加await關鍵字,但是沒有用
Thread myThread = new Thread(new ThreadStart(()=> await Download.file(uri)));
Thread myThread = new Thread(new ThreadStart(()=>Download.file(uri)));
myThread.Start();
myThread.Join();
class Download{
public static async void file(string url)
{
try
{
HttpWebRequest request;
HttpWebResponse webResponse = null;
request = HttpWebRequest.CreateHttp(url);
request.AllowReadStreamBuffering = true;
webResponse = await request.GetResponseAsync() as HttpWebResponse;
Stream responseStream = webResponse.GetResponseStream();
using (StreamReader reader = new StreamReader(responseStream))
{
string content = await reader.ReadToEndAsync();
}
webResponse.Close();
}
catch (Exception ex) {
Debug.WriteLine(ex.Message);
}
}
}
謝謝
您應該使您的file
方法(順便說一句,它的名稱很錯誤-可能類似於DownloadFileAsync
)返回Task
而不是void
。
然后,您可以等待。
但是,目前還不清楚為什么你會在不同的線程反正開始本-異步的一點是,你並不需要開始一個新的線程。 通過另一種異步方法,您可以使用:
await Download.file(uri);
(當然,該方法沒有對內容做任何事情的事實有點奇怪……)
您還應該考慮使用HttpClient
或WebClient
,它們都已具有此行為。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.