backgroundworker
-
Hi, A few weeks back i was trying to implement backgroundworker. I got a good code sample but i still didn't managed to get it to work. I messed up my whole code. Nothing was working anymore. So i had to work on my backupped project. Now i got it back as how it was again. I was kinda hoping if someone could help me again with it. Some comments would be really appreciated (in plain English). This is my whole class: public partial class FrmWordDisplayer : Form { public FrmWordDisplayer() { InitializeComponent(); this.FormClosing += new FormClosingEventHandler(FrmWordDisplayer_FormClosing); } private void FrmWordDisplayer_FormClosing(object sender, FormClosingEventArgs e) { DialogResult result = MessageBox.Show("wanna close?", "Conformation", MessageBoxButtons.YesNo, MessageBoxIcon.Information); if (result == DialogResult.Yes) { e.Cancel = false; this.Dispose(); } else if (result == DialogResult.No) { e.Cancel = true; } } public void DisplayWord() { Show(); FileStream smallWords = File.Open(@"smallwords.txt", FileMode.Open, FileAccess.Read); StreamReader rdr = new StreamReader(smallWords); Random rnd = new Random(); string sDocument = rdr.ReadToEnd(); rdr.Close(); smallWords.Close(); string[] words = sDocument.Replace('\r', ' ').Replace('\n', ' ').Split(';'); while(true) { int numberChosen = rnd.Next(0, words.Length - 1); this.lblDisplayWord.Text = words[numberChosen].ToString(); this.lblDisplayWord.Update(); Application.DoEvents(); Thread.Sleep(1000); } } } This is a second Form in my project. On my fist Form i got a few buttons. One of them, represents this Form. When this button is pressed, it execute this method: public void DisplayWord() and keeps displaying words until the user closes the Form. But the Form still hangs. Thats why i want to implement the backgroundworker. It makes it possible the be in control of the Form the whole time. Its this peace of code that makes the Form running slow and hang: while(true) { int numberChosen = rnd.Next(0, words.Length - 1);
-
Hi, A few weeks back i was trying to implement backgroundworker. I got a good code sample but i still didn't managed to get it to work. I messed up my whole code. Nothing was working anymore. So i had to work on my backupped project. Now i got it back as how it was again. I was kinda hoping if someone could help me again with it. Some comments would be really appreciated (in plain English). This is my whole class: public partial class FrmWordDisplayer : Form { public FrmWordDisplayer() { InitializeComponent(); this.FormClosing += new FormClosingEventHandler(FrmWordDisplayer_FormClosing); } private void FrmWordDisplayer_FormClosing(object sender, FormClosingEventArgs e) { DialogResult result = MessageBox.Show("wanna close?", "Conformation", MessageBoxButtons.YesNo, MessageBoxIcon.Information); if (result == DialogResult.Yes) { e.Cancel = false; this.Dispose(); } else if (result == DialogResult.No) { e.Cancel = true; } } public void DisplayWord() { Show(); FileStream smallWords = File.Open(@"smallwords.txt", FileMode.Open, FileAccess.Read); StreamReader rdr = new StreamReader(smallWords); Random rnd = new Random(); string sDocument = rdr.ReadToEnd(); rdr.Close(); smallWords.Close(); string[] words = sDocument.Replace('\r', ' ').Replace('\n', ' ').Split(';'); while(true) { int numberChosen = rnd.Next(0, words.Length - 1); this.lblDisplayWord.Text = words[numberChosen].ToString(); this.lblDisplayWord.Update(); Application.DoEvents(); Thread.Sleep(1000); } } } This is a second Form in my project. On my fist Form i got a few buttons. One of them, represents this Form. When this button is pressed, it execute this method: public void DisplayWord() and keeps displaying words until the user closes the Form. But the Form still hangs. Thats why i want to implement the backgroundworker. It makes it possible the be in control of the Form the whole time. Its this peace of code that makes the Form running slow and hang: while(true) { int numberChosen = rnd.Next(0, words.Length - 1);
The BackgroundWorker class allows you to run an operation on a separate, dedicated thread. Time-consuming operations like downloads and database transactions can cause your user interface (UI) to seem as though it has stopped responding while they are running. When you want a responsive UI and you are faced with long delays associated with such operations, the BackgroundWorker class provides a convenient solution. To execute a time-consuming operation in the background, create a BackgroundWorker and listen for events that report the progress of your operation and signal when your operation is finished. You can create the BackgroundWorker programmatically or you can drag it onto your form from the Components tab of the Toolbox. If you create the BackgroundWorker in the Windows Forms Designer, it will appear in the Component Tray, and its properties will be displayed in the Properties window. To set up for a background operation, add an event handler for the DoWork event. Call your time-consuming operation in this event handler. To start the operation, call RunWorkerAsync. To receive notifications of progress updates, handle the ProgressChanged event. To receive a notification when the operation is completed, handle the RunWorkerCompleted event.
I can not see BackroundWorker.RunAsync() method in your code, you must trigger your background worker with this method. In MSDN there are useful examples.
using System; using System.Collections; using System.ComponentModel; using System.Drawing; using System.Threading; using System.Windows.Forms; namespace BackgroundWorkerExample { public class FibonacciForm : System.Windows.Forms.Form { private int numberToCompute = 0; private int highestPercentageReached = 0; private System.Windows.Forms.NumericUpDown numericUpDown1; private System.Windows.Forms.Button startAsyncButton; private System.Windows.Forms.Button cancelAsyncButton; private System.Windows.Forms.ProgressBar progressBar1; private System.Windows.Forms.Label resultLabel; private System.ComponentModel.BackgroundWorker backgroundWorker1; public FibonacciForm() { InitializeComponent(); InitializeBackgoundWorker(); } // Set up the BackgroundWorker object by // attaching event handlers. private void InitializeBackgoundWorker() { backgroundWorker1.
-
Hi, A few weeks back i was trying to implement backgroundworker. I got a good code sample but i still didn't managed to get it to work. I messed up my whole code. Nothing was working anymore. So i had to work on my backupped project. Now i got it back as how it was again. I was kinda hoping if someone could help me again with it. Some comments would be really appreciated (in plain English). This is my whole class: public partial class FrmWordDisplayer : Form { public FrmWordDisplayer() { InitializeComponent(); this.FormClosing += new FormClosingEventHandler(FrmWordDisplayer_FormClosing); } private void FrmWordDisplayer_FormClosing(object sender, FormClosingEventArgs e) { DialogResult result = MessageBox.Show("wanna close?", "Conformation", MessageBoxButtons.YesNo, MessageBoxIcon.Information); if (result == DialogResult.Yes) { e.Cancel = false; this.Dispose(); } else if (result == DialogResult.No) { e.Cancel = true; } } public void DisplayWord() { Show(); FileStream smallWords = File.Open(@"smallwords.txt", FileMode.Open, FileAccess.Read); StreamReader rdr = new StreamReader(smallWords); Random rnd = new Random(); string sDocument = rdr.ReadToEnd(); rdr.Close(); smallWords.Close(); string[] words = sDocument.Replace('\r', ' ').Replace('\n', ' ').Split(';'); while(true) { int numberChosen = rnd.Next(0, words.Length - 1); this.lblDisplayWord.Text = words[numberChosen].ToString(); this.lblDisplayWord.Update(); Application.DoEvents(); Thread.Sleep(1000); } } } This is a second Form in my project. On my fist Form i got a few buttons. One of them, represents this Form. When this button is pressed, it execute this method: public void DisplayWord() and keeps displaying words until the user closes the Form. But the Form still hangs. Thats why i want to implement the backgroundworker. It makes it possible the be in control of the Form the whole time. Its this peace of code that makes the Form running slow and hang: while(true) { int numberChosen = rnd.Next(0, words.Length - 1);
It looks to me like you would be better off just using a timer. But, maybe you are doing an exercise in multithreading. In which case, it doesn't look like you've created a separate thread anywhere. Something like this might be closer to what you are trying to do:
public partial class frmWordDisplayer : Form
{
private Thread tMyThread;
delegate void SetlabelCallback(string cCaption);public frmWordDisplayer() { InitializeComponent(); this.FormClosing += new FormClosingEventHandler(FrmWordDisplayer\_FormClosing); } private void FrmWordDisplayer\_FormClosing(object sender, FormClosingEventArgs e) { DialogResult result = MessageBox.Show("wanna close?","Conformation", MessageBoxButtons.YesNo, MessageBoxIcon.Information); if (result == DialogResult.Yes) { e.Cancel = false; tMyThread.Abort(); this.Dispose(); } else if (result == DialogResult.No) { e.Cancel = true; } } public void DisplayWord() { Show(); tMyThread = new Thread(new ThreadStart(DisplayWordThread)); tMyThread.Start(); } private void DisplayWordThread() { FileStream smallWords = File.Open(@"smallwords.txt", FileMode.Open, FileAccess.Read); StreamReader rdr = new StreamReader(smallWords); Random rnd = new Random(); string sDocument = rdr.ReadToEnd(); rdr.Close(); smallWords.Close(); string\[\] words = sDocument.Replace('\\r', ' ').Replace('\\n', ' ').Split(';'); while(true) { int numberChosen = rnd.Next(0, words.Length - 1); SetLabelCaption(words\[numberChosen\].ToString()); Thread.Sleep(1000); } } private void SetLabelCaption(String cCaption) { if (this.lblDisplayWord.InvokeRequired) { SetlabelCallback d = new SetlabelCallback(SetLabelCaption); this.Invoke(d, new object\[\] { cCaption }); } else { this.lblDisplayWord.Text = cCaption; this.lblDisplayWord.Update(); } }
}
--EricDV Sig--------- Some problems are so complex that you have to be highly intelligent and well informed just to be undecided about them. - Laurence J. Peters
-
The BackgroundWorker class allows you to run an operation on a separate, dedicated thread. Time-consuming operations like downloads and database transactions can cause your user interface (UI) to seem as though it has stopped responding while they are running. When you want a responsive UI and you are faced with long delays associated with such operations, the BackgroundWorker class provides a convenient solution. To execute a time-consuming operation in the background, create a BackgroundWorker and listen for events that report the progress of your operation and signal when your operation is finished. You can create the BackgroundWorker programmatically or you can drag it onto your form from the Components tab of the Toolbox. If you create the BackgroundWorker in the Windows Forms Designer, it will appear in the Component Tray, and its properties will be displayed in the Properties window. To set up for a background operation, add an event handler for the DoWork event. Call your time-consuming operation in this event handler. To start the operation, call RunWorkerAsync. To receive notifications of progress updates, handle the ProgressChanged event. To receive a notification when the operation is completed, handle the RunWorkerCompleted event.
I can not see BackroundWorker.RunAsync() method in your code, you must trigger your background worker with this method. In MSDN there are useful examples.
using System; using System.Collections; using System.ComponentModel; using System.Drawing; using System.Threading; using System.Windows.Forms; namespace BackgroundWorkerExample { public class FibonacciForm : System.Windows.Forms.Form { private int numberToCompute = 0; private int highestPercentageReached = 0; private System.Windows.Forms.NumericUpDown numericUpDown1; private System.Windows.Forms.Button startAsyncButton; private System.Windows.Forms.Button cancelAsyncButton; private System.Windows.Forms.ProgressBar progressBar1; private System.Windows.Forms.Label resultLabel; private System.ComponentModel.BackgroundWorker backgroundWorker1; public FibonacciForm() { InitializeComponent(); InitializeBackgoundWorker(); } // Set up the BackgroundWorker object by // attaching event handlers. private void InitializeBackgoundWorker() { backgroundWorker1.
-
It looks to me like you would be better off just using a timer. But, maybe you are doing an exercise in multithreading. In which case, it doesn't look like you've created a separate thread anywhere. Something like this might be closer to what you are trying to do:
public partial class frmWordDisplayer : Form
{
private Thread tMyThread;
delegate void SetlabelCallback(string cCaption);public frmWordDisplayer() { InitializeComponent(); this.FormClosing += new FormClosingEventHandler(FrmWordDisplayer\_FormClosing); } private void FrmWordDisplayer\_FormClosing(object sender, FormClosingEventArgs e) { DialogResult result = MessageBox.Show("wanna close?","Conformation", MessageBoxButtons.YesNo, MessageBoxIcon.Information); if (result == DialogResult.Yes) { e.Cancel = false; tMyThread.Abort(); this.Dispose(); } else if (result == DialogResult.No) { e.Cancel = true; } } public void DisplayWord() { Show(); tMyThread = new Thread(new ThreadStart(DisplayWordThread)); tMyThread.Start(); } private void DisplayWordThread() { FileStream smallWords = File.Open(@"smallwords.txt", FileMode.Open, FileAccess.Read); StreamReader rdr = new StreamReader(smallWords); Random rnd = new Random(); string sDocument = rdr.ReadToEnd(); rdr.Close(); smallWords.Close(); string\[\] words = sDocument.Replace('\\r', ' ').Replace('\\n', ' ').Split(';'); while(true) { int numberChosen = rnd.Next(0, words.Length - 1); SetLabelCaption(words\[numberChosen\].ToString()); Thread.Sleep(1000); } } private void SetLabelCaption(String cCaption) { if (this.lblDisplayWord.InvokeRequired) { SetlabelCallback d = new SetlabelCallback(SetLabelCaption); this.Invoke(d, new object\[\] { cCaption }); } else { this.lblDisplayWord.Text = cCaption; this.lblDisplayWord.Update(); } }
}
--EricDV Sig--------- Some problems are so complex that you have to be highly intelligent and well informed just to be undecided about them. - Laurence J. Peters
Hi EricDV, Thank you for your reply! I was using the Application.DoEvents() method to be able to keep control over the Form in my while statement. But it still the tendency to "hang". So i've been told to use the backgroundworker which makes the user able to have control over the Form all the time. I did want to use the multi thread too, but i've been advised not to do so. Also i really want to learn this backgroundworker, sounds like a very usefull "thing". If there is any one that could help me with backgroundworker, i'll be very gratefull! Thanks in advance!
-
Hi, A few weeks back i was trying to implement backgroundworker. I got a good code sample but i still didn't managed to get it to work. I messed up my whole code. Nothing was working anymore. So i had to work on my backupped project. Now i got it back as how it was again. I was kinda hoping if someone could help me again with it. Some comments would be really appreciated (in plain English). This is my whole class: public partial class FrmWordDisplayer : Form { public FrmWordDisplayer() { InitializeComponent(); this.FormClosing += new FormClosingEventHandler(FrmWordDisplayer_FormClosing); } private void FrmWordDisplayer_FormClosing(object sender, FormClosingEventArgs e) { DialogResult result = MessageBox.Show("wanna close?", "Conformation", MessageBoxButtons.YesNo, MessageBoxIcon.Information); if (result == DialogResult.Yes) { e.Cancel = false; this.Dispose(); } else if (result == DialogResult.No) { e.Cancel = true; } } public void DisplayWord() { Show(); FileStream smallWords = File.Open(@"smallwords.txt", FileMode.Open, FileAccess.Read); StreamReader rdr = new StreamReader(smallWords); Random rnd = new Random(); string sDocument = rdr.ReadToEnd(); rdr.Close(); smallWords.Close(); string[] words = sDocument.Replace('\r', ' ').Replace('\n', ' ').Split(';'); while(true) { int numberChosen = rnd.Next(0, words.Length - 1); this.lblDisplayWord.Text = words[numberChosen].ToString(); this.lblDisplayWord.Update(); Application.DoEvents(); Thread.Sleep(1000); } } } This is a second Form in my project. On my fist Form i got a few buttons. One of them, represents this Form. When this button is pressed, it execute this method: public void DisplayWord() and keeps displaying words until the user closes the Form. But the Form still hangs. Thats why i want to implement the backgroundworker. It makes it possible the be in control of the Form the whole time. Its this peace of code that makes the Form running slow and hang: while(true) { int numberChosen = rnd.Next(0, words.Length - 1);
My BackgroundWorker experience is not so much but as I understood from MSDN, your code implemeantation is wrong. I think instead of "Application.DoEvents()" you can use "FormClosing.RunAsync()" method where you want your BW to start. For instance you can put this method in the other Form constructor. Calling "FormClosing.RunAsync()" starts your thread, thread will stop when it finishes its job or when you wants to stopped it. Since I dont know your whole code, I cant give exact code examples.