Reputation: 297
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
Upvotes: 2
Views: 306
Reputation: 1499740
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.
Upvotes: 5