简体   繁体   中英

How wait asynchronous method in a thread?

I need that Join method is called when Download.file method have finished. I tried to add await keyword but it didn't work

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 .

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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