In my program I am using a separate thread to read from an external file and convey data to my program. I am in the process of trying to run a ProgressBar
on the UI thread while that thread is running, in order to provide feedback to the user. As of now, I have a ProgressBar
that opens, but does not close because I do not know how to tell it that the child thread has ended. I have read this tutorial on ProgressBars, and should make a note that I am not using a BackgroundWorker
for my thread. Instead of this, I am just using a System.Threading.Thread
. Please let me know if this is a problem.
The OpenFile()
method that opens the Window containing the ProgressBar
, and also launches the thread that will do the open file work:
public void OpenFile()
{
//Open Progress Bar Window
LoadingWindow = new LoadingScreen(App.MainWindowViewModel.LoadScreen);
LoadingWindow.Show();
App.MainWindowViewModel.LoadScreen.IsIndeterminate = true;
FILE_INPUT = true; //bool that Signifies that the background thread is running
//Create Thread -- run routines in thread
var openFileThread = new Thread(() => openDefault(txtFile)); //Passes the file
openFileThread.Start(); //Start File open thread
}
//This thread reads in the file and transfers the data to the program
private void openDefault(StreamReader txtFile)
{
//Gathers info from file and changes program accordingly
FILE_INPUT = false; //background thread is no longer running
}
As of now, I do not have an increment method for my ProgressBar
, as I would like to make sure that I can get it working correctly before working on a technical detail like that. Anyway, my question is... how and where in my program do I make it known that the background thread is done running and the LoadingWindow
(ProgressBar
) can be closed?
Some more code to help give you an idea of my program's flow:
Main Window Code Behind:
private void OpenFile_Click(object sender, RoutedEventArgs e)
{
OpenFile(); //calls to the method that launches the new thread and the window with the Progress Bar
//Wait until background Thread is complete
while (ViewModel.FILE_INPUT == true) { }
//After thread has stopped running, close the window (DOES NOT WORK)
ViewModel.LoadingWindow.Close(); // -- Close Prog Bar
}
Eventual Solution:
//In OpenFile() method
LoadingWindow = new LoadingScreen(App.MainWindowViewModel.LoadScreen); //Open Progress Bar Window
LoadingWindow.Show();
App.MainWindowViewModel.LoadScreen.IsIndeterminate = true;
FILE_INPUT = true; //A file is being inputted*
Dispatcher UIDispatcher = Dispatcher.CurrentDispatcher;
Task.Factory.StartNew(() =>
{
openDefault(txtFile); //Passes the file
//After thread has stopped running, close the Loading Window
UIDispatcher.Invoke((Action)(() => LoadingWindow.Close())); //Close progress bar
});