简体   繁体   English

如何在线程中等待异步方法?

[英]How wait asynchronous method in a thread?

I need that Join method is called when Download.file method have finished. 我需要在Download.file方法完成后调用Join方法。 I tried to add await keyword but it didn't work 我试图添加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);
        }
    }
}

Thanks 谢谢

You should make your file method (which is badly named, by the way - it should probably be something like DownloadFileAsync ) return Task instead of void . 您应该使您的file方法(顺便说一句,它的名称很错误-可能类似于DownloadFileAsync )返回Task而不是void

Then you can await it. 然后,您可以等待。

However, it's not clear why you're starting this in a different thread anyway - the point of asynchrony is that you don't need to start a new thread. 但是,目前还不清楚为什么你会在不同的线程反正开始本-异步的一点是,你并不需要开始一个新的线程。 From another async method, you can just use: 通过另一种异步方法,您可以使用:

await Download.file(uri);

(Of course the fact that the method isn't doing anything with the content is a little strange...) (当然,该方法没有对内容做任何事情的事实有点奇怪……)

You should also consider using HttpClient or WebClient , both of which have this behaviour already available. 您还应该考虑使用HttpClientWebClient ,它们都已具有此行为。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM