Reputation: 339
i have a problem with threads, i have this code (example):
private void button_Click(object sender, EventArgs e) {
ShowMessage("Starting Downloads...");
<more code>
StartDownloads();
RunFileDownload();
<more code>
}
private void StartDownloads() {
<more code>
for (int i=0; i<10; i++) {
ShowMessage("Downloading file: " + i);
Download(i);
<more code>
}
<more code>
}
The problem is, when i press the button and the downloading starts, the messages are not displayed... I tried to fix it with threads, like this:
private void button_Click(object sender, EventArgs e) {
ShowMessage("Starting Downloads...");
Thread t = new Thread(new ThreadStart(StartDownloads));
t.Start();
RunFileDownload();
}
But the RunFileDownload(); function starts before the files are downloaded. I try solve this with "Thread.Join();" but again not displayed messages (The main thread is paused).
I thought solve it with a multi-thread and Thread.Join(); but it isn't efficient and i will have problems with others functions in the main thread.
How can i solve this problem? Thanks.
Edit #2:
Considering this code:
private void Download() {
ShowMessage("Starting Downloads...");
Thread t = new Thread(new ThreadStart(StartDownloads));
ShowMessage("Downloads Finished..."); | not run until
RunFileDownload(); | finished
ShowMessage("Files Executed..."); | thread.
}
How can i expect the thread finish before the rest of the code is executed? I try with Thread.Join(); but it freezes the application.
Upvotes: 2
Views: 2976
Reputation: 61339
Assuming you have access to async
/await
, the simplest solution is this:
private async void button_Click(object sender, EventArgs e)
{
ShowMessage("Starting Downloads...");
await StartDownloads(); //Return control until this method completes!
RunFileDownload();
}
Note that exceptions with await
are, suffice it to say, less than kind. Please ensure that you are using proper try/catch blocks, especially from await
onwards. Consider using this pattern: Fire-and-forget with async vs "old async delegate" and reading this article.
Note that StartDownloads
needs to be async and return a Task
for this to work.
Apart from that solution, you need the thread to invoke a callback or raise an event on completion so you can run RunFileDownload
. Using a BackgroundWorker
can simplify that process.
Upvotes: 5