I am very very new to WPF. I looked in the internet for several examples and tutorials about threading. They\'ve their own way to describe. But for naive like me, I want to
You need to use the BackgroundWorker for your long running task and use Dispatcher to update UI in between
//create background worker
BackgroundWorker worker = new BackgroundWorker();
//assign it work
worker.DoWork += new DoWorkEventHandler(worker_DoWork);
//start work
worker.RunWorkerAsync();
//this work will be done in background
void worker_DoWork(object sender, DoWorkEventArgs e)
{
SET initial = 0;
SET maxData = 1000
DO UNTIL initial <1000
CREATE db query "INSERT INTO (col1,col2,col3) VALUES(value1,value2,value3);"
//in between your work do this to update label
label.Dispatcher.Invoke(System.Windows.Threading.DispatcherPriority.Normal,new Action(delegate()
{
Label.Content = "SomeValue";
}
));
END DO
}
Here is sample code snippet to handle WPF threading..
Consider this scenario.
we have to get some data from the server and after that we have play with data. means our next action is completely dependent on the callback or completion of Task.
in this case we can use task factory ContinueWith method like following
ObservableCollection images = new ObservableCollection();
TaskFactory tFactory = new TaskFactory();
tFactory.StartNew(() =>
{
for (int i = 0; i < 50; i++)
{
//GET IMAGE Path FROM SERVER
System.Windows.Application.Current.Dispatcher.BeginInvoke((Action)delegate()
{
// UPDATE PROGRESS BAR IN UI
});
images.Add(("");
}
}).ContinueWith(t =>
{
if (t.IsFaulted)
{
// EXCEPTION IF THREAD IS FAULT
throw t.Exception;
}
System.Windows.Application.Current.Dispatcher.BeginInvoke((Action)delegate()
{
//PROCESS IMAGES AND DISPLAY
});
});
Multithreading hasn't anything to deal with the UI techinque you are choosing (Wpf or Winforms) - there are only slight differences when you have to switch to the UI thread to update your controls.
According to your code sample, I must say, that there is no callback possibility from sql server to your program. If you want to have that feature, you have to implement the loop in C# not in a sql statement.
Edit:
According to the comment of OP I add a sample of background working and updating UI in foreground with TPL (Task Parallel Library):
var task = new Task(() =>
{
// Do something very long ...
});
task.ContinueWith((previousTask) =>
{
label.Content = "Background work has finished.";
},
TaskScheduler.FromCurrentSynchronizationContext());
label.Content = "Background work is running.";
task.Start();