Reputation: 867
My program has a thread that executes commands based on user input. Sometimes, the commands can take a while to run.
So I need to start a thread for the long running tasks in order to allow the user to continue working.
After Googling for a bit, I found tasks, and made the code below:
private Thread t_Thread;
private void startTask()
{
Console.WriteLine("Starting");
Task t = Task.Factory.StartNew(() =>
{
for (int i = 0; i <= 4; i++)
{
Console.WriteLine(i);
Thread.Sleep(500); // Is this right?
}
});
Task.WaitAny(t);
Console.WriteLine("Ending");
}
private void button1_Click(object sender, EventArgs e)
{
t_Thread = new Thread(() => startTask());
t_Thread.Start();
}
It seems to work okay but I'm unsure if I'm doing it right. Something tells me I've approached this wrong. Did I?
Upvotes: 0
Views: 108
Reputation: 2709
It sounds like you want something like the BackgroundWorker. It has a method RunWorkerAsync()
which causes its DoWork
event to be thrown; all of DoWork
's event handlers are executed in a different thread.
When the work is done, the BackgroundWorker
throws its RunWorkerCompleted
event, which you can listen to back on the UI thread.
In the mean time, the main form should be responsive to user input. If you don't want to accept user input, you can just disable all the controls before calling RunWorkerAsync
, and re-enable them in the RunWorkerCompleted
event handler.
Upvotes: 4
Reputation: 88064
If your program is supposed to stop and wait until the task finishes then you shouldn't be using threads. Instead just change the cursor to an hourglass and execute it in the main thread.
Other than that you will likely want to evaluate why things take so long and determine if the application is really supposed to sit there until it's done.
Upvotes: 1