I'm having some issues while waiting for a ThreadState during the Click event of a button control.
Whenever I click my button it'll execute the code below.
The problem with this is that it won't wait until the ThreadState is "Stopped", so it never enables btnImportData or btnExportBellijst.
I've tried t.Join() but that freezes my whole form and I use a RichTextBox as logger, so that'd result in a logger that freezes for a few seconds and then shows a lot of text at once.
The reason I put the ImportData function on another Thread is to keep the form running so people can see the logs happening realtime.
What I'd like to have when I click my button:
- Change
Enabledof 1 or more buttons. - Run my function
ImportDataon another thread so my logger can keep logging. (void ImportData(){}) Change
Enabledof 1 or more buttons after my function is done doing something.private void btnImportData_Click(object sender, EventArgs e) { //Disable current button btnImportData.Enabled = false; imgBonne.Visible = false; //random image rtConsole.Visible = true; //RichTextBox logger //Create a new thread for the button function var t = new Thread(ImportData); t.Start(); //It does NOT wait until thread stopped while (t.ThreadState == ThreadState.Stopped) { //Never gets executed btnImportData.Enabled = true; btnExportBellijst.Enabled = true; } }
Extra Info: Screenshot from before pressing "Import Data": http://puu.sh/88oD6.png Screenshot from after the application is done importing data: http://puu.sh/88oNT.png
(edit)Target framework: .NET Framework 4
I was originally using the code below, but this instantly enables all the buttons after pressing "Import Data".
private void btnImportData_Click(object sender, EventArgs e)
{
imgBonne.Visible = false; //random image
rtConsole.Visible = true; //RichTextBox logger
var t = new Thread(ImportData);
t.Start();
while (t.ThreadState == ThreadState.Running)
{
btnImportData.Enabled = false;
}
btnImportData.Enabled = true;
btnExportBellijst.Enabled = true;
}
Edit: I'm sorry if this is in the wrong category, I wanted to put it in c#.