What is the simplest way to implement multithreading in c# to existing code
Posted
by
Kaeso
on Stack Overflow
See other posts from Stack Overflow
or by Kaeso
Published on 2011-01-08T01:38:32Z
Indexed on
2011/01/08
13:54 UTC
Read the original article
Hit count: 220
I have already implemented a functionnal application that parses 26 pages of html all at once to produce an xml file with data contained on the web pages. I would need to implement a thread so that this method can work in the background without causing my app to seems unresponsive.
Secondly, I have another function that is decoupled from the first one which compares two xml files to produce a third one and then transform this third xml file to produce an html page using XSLT. This would have to be on a thread, where I can click Cancel to stop the thread whithout crashing the app.
What is the easiest best way to do this using WPF forms in VS 2010 ?
I have chosen to use the BackgroundWorker.
BackgroundWorker implementation:
public partial class MainWindow : Window
{
private BackgroundWorker bw = new BackgroundWorker();
public MainWindow()
{
InitializeComponent();
bw.WorkerReportsProgress = true;
bw.DoWork += new DoWorkEventHandler(bw_DoWork);
bw.RunWorkerCompleted += new RunWorkerCompletedEventHandler(backgroundWorker1_RunWorkerCompleted);
}
private void Window_Loaded(object sender, RoutedEventArgs e)
{
this.LoadFiles();
}
private void btnCompare_Click(object sender, EventArgs e)
{
if (bw.IsBusy != true)
{
progressBar2.IsIndeterminate = true;
// Start the asynchronous operation.
bw.RunWorkerAsync();
}
}
private void bw_DoWork(object sender, DoWorkEventArgs e)
{
StatsProcessor proc = new StatsProcessor();
if (lstStatsBox1.SelectedItem != null)
if (lstStatsBox2.SelectedItem != null)
proc.CompareStats(lstStatsBox1.SelectedItem.ToString(), lstStatsBox2.SelectedItem.ToString());
}
private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
progressBar2.IsIndeterminate = false;
progressBar2.Value = 100;
}
I have started with the bgworker solution, but it seems that the bw_DoWork method is never called when btnCompare is clicked, I must be doing something wrong... I am new to threads.
© Stack Overflow or respective owner