[英]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.