Click here to Skip to main content
15,886,199 members
Home / Discussions / C#
   

C#

 
AnswerRe: (220v Relay), please help Pin
coolestCoder5-Nov-06 23:48
coolestCoder5-Nov-06 23:48 
GeneralRe: (220v Relay), please help Pin
Muammar©7-Nov-06 20:57
Muammar©7-Nov-06 20:57 
AnswerRe: (220v Relay), please help Pin
cjengler6-Nov-06 0:06
cjengler6-Nov-06 0:06 
GeneralRe: (220v Relay), please help Pin
Muammar©7-Nov-06 20:54
Muammar©7-Nov-06 20:54 
GeneralRe: (220v Relay), please help Pin
Guffa6-Nov-06 1:15
Guffa6-Nov-06 1:15 
QuestionUse Style Builder dialog box? Pin
Gywox5-Nov-06 23:35
Gywox5-Nov-06 23:35 
Questionbackgroundworker Pin
Yustme5-Nov-06 23:24
Yustme5-Nov-06 23:24 
AnswerRe: backgroundworker Pin
mertkan656-Nov-06 4:27
mertkan656-Nov-06 4:27 
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;<br />
using System.Collections;<br />
using System.ComponentModel;<br />
using System.Drawing;<br />
using System.Threading;<br />
using System.Windows.Forms;<br />
<br />
namespace BackgroundWorkerExample<br />
{	<br />
    public class FibonacciForm : System.Windows.Forms.Form<br />
    {	<br />
        private int numberToCompute = 0;<br />
        private int highestPercentageReached = 0;<br />
<br />
        private System.Windows.Forms.NumericUpDown numericUpDown1;<br />
        private System.Windows.Forms.Button startAsyncButton;<br />
        private System.Windows.Forms.Button cancelAsyncButton;<br />
        private System.Windows.Forms.ProgressBar progressBar1;<br />
        private System.Windows.Forms.Label resultLabel;<br />
        private System.ComponentModel.BackgroundWorker backgroundWorker1;<br />
<br />
        public FibonacciForm()<br />
        {	<br />
            InitializeComponent();<br />
<br />
            InitializeBackgoundWorker();<br />
        }<br />
<br />
        // Set up the BackgroundWorker object by <br />
        // attaching event handlers. <br />
        private void InitializeBackgoundWorker()<br />
        {<br />
            backgroundWorker1.DoWork += <br />
                new DoWorkEventHandler(backgroundWorker1_DoWork);<br />
            backgroundWorker1.RunWorkerCompleted += <br />
                new RunWorkerCompletedEventHandler(<br />
            backgroundWorker1_RunWorkerCompleted);<br />
            backgroundWorker1.ProgressChanged += <br />
                new ProgressChangedEventHandler(<br />
            backgroundWorker1_ProgressChanged);<br />
        }<br />
	<br />
        private void startAsyncButton_Click(System.Object sender, <br />
            System.EventArgs e)<br />
        {<br />
            // Reset the text in the result label.<br />
            resultLabel.Text = String.Empty;<br />
<br />
            // Disable the UpDown control until <br />
            // the asynchronous operation is done.<br />
            this.numericUpDown1.Enabled = false;<br />
<br />
            // Disable the Start button until <br />
            // the asynchronous operation is done.<br />
            this.startAsyncButton.Enabled = false;<br />
<br />
            // Enable the Cancel button while <br />
            // the asynchronous operation runs.<br />
            this.cancelAsyncButton.Enabled = true;<br />
<br />
            // Get the value from the UpDown control.<br />
            numberToCompute = (int)numericUpDown1.Value;<br />
<br />
            // Reset the variable for percentage tracking.<br />
            highestPercentageReached = 0;<br />
<br />
            // Start the asynchronous operation.<br />
            backgroundWorker1.RunWorkerAsync(numberToCompute);<br />
        }<br />
<br />
        private void cancelAsyncButton_Click(System.Object sender, <br />
            System.EventArgs e)<br />
        {   <br />
            // Cancel the asynchronous operation.<br />
            this.backgroundWorker1.CancelAsync();<br />
<br />
            // Disable the Cancel button.<br />
            cancelAsyncButton.Enabled = false;<br />
        }<br />
<br />
        // This event handler is where the actual,<br />
        // potentially time-consuming work is done.<br />
        private void backgroundWorker1_DoWork(object sender, <br />
            DoWorkEventArgs e)<br />
        {   <br />
            // Get the BackgroundWorker that raised this event.<br />
            BackgroundWorker worker = sender as BackgroundWorker;<br />
<br />
            // Assign the result of the computation<br />
            // to the Result property of the DoWorkEventArgs<br />
            // object. This is will be available to the <br />
            // RunWorkerCompleted eventhandler.<br />
            e.Result = ComputeFibonacci((int)e.Argument, worker, e);<br />
        }<br />
<br />
        // This event handler deals with the results of the<br />
        // background operation.<br />
        private void backgroundWorker1_RunWorkerCompleted(<br />
            object sender, RunWorkerCompletedEventArgs e)<br />
        {<br />
            // First, handle the case where an exception was thrown.<br />
            if (e.Error != null)<br />
            {<br />
                MessageBox.Show(e.Error.Message);<br />
            }<br />
            else if (e.Cancelled)<br />
            {<br />
                // Next, handle the case where the user canceled <br />
                // the operation.<br />
                // Note that due to a race condition in <br />
                // the DoWork event handler, the Cancelled<br />
                // flag may not have been set, even though<br />
                // CancelAsync was called.<br />
                resultLabel.Text = "Canceled";<br />
            }<br />
            else<br />
            {<br />
                // Finally, handle the case where the operation <br />
                // succeeded.<br />
                resultLabel.Text = e.Result.ToString();<br />
            }<br />
<br />
            // Enable the UpDown control.<br />
            this.numericUpDown1.Enabled = true;<br />
<br />
            // Enable the Start button.<br />
            startAsyncButton.Enabled = true;<br />
<br />
            // Disable the Cancel button.<br />
            cancelAsyncButton.Enabled = false;<br />
        }<br />
<br />
        // This event handler updates the progress bar.<br />
        private void backgroundWorker1_ProgressChanged(object sender,<br />
            ProgressChangedEventArgs e)<br />
        {<br />
            this.progressBar1.Value = e.ProgressPercentage;<br />
        }<br />
<br />
        // This is the method that does the actual work. For this<br />
        // example, it computes a Fibonacci number and<br />
        // reports progress as it does its work.<br />
        long ComputeFibonacci(int n, BackgroundWorker worker, DoWorkEventArgs e)<br />
        {<br />
            // The parameter n must be >= 0 and <= 91.<br />
            // Fib(n), with n > 91, overflows a long.<br />
            if ((n < 0) || (n > 91))<br />
            {<br />
                throw new ArgumentException(<br />
                    "value must be >= 0 and <= 91", "n");<br />
            }<br />
<br />
            long result = 0;<br />
<br />
            // Abort the operation if the user has canceled.<br />
            // Note that a call to CancelAsync may have set <br />
            // CancellationPending to true just after the<br />
            // last invocation of this method exits, so this <br />
            // code will not have the opportunity to set the <br />
            // DoWorkEventArgs.Cancel flag to true. This means<br />
            // that RunWorkerCompletedEventArgs.Cancelled will<br />
            // not be set to true in your RunWorkerCompleted<br />
            // event handler. This is a race condition.<br />
<br />
            if (worker.CancellationPending)<br />
            {   <br />
                e.Cancel = true;<br />
            }<br />
            else<br />
            {   <br />
                if (n < 2)<br />
                {   <br />
                    result = 1;<br />
                }<br />
                else<br />
                {   <br />
                    result = ComputeFibonacci(n - 1, worker, e) + <br />
                             ComputeFibonacci(n - 2, worker, e);<br />
                }<br />
<br />
                // Report progress as a percentage of the total task.<br />
                int percentComplete = <br />
                    (int)((float)n / (float)numberToCompute * 100);<br />
                if (percentComplete > highestPercentageReached)<br />
                {<br />
                    highestPercentageReached = percentComplete;<br />
                    worker.ReportProgress(percentComplete);<br />
                }<br />
            }<br />
<br />
            return result;<br />
        }<br />
<br />
<br />
		#region Windows Form Designer generated code<br />
		<br />
        private void InitializeComponent()<br />
        {<br />
            this.numericUpDown1 = new System.Windows.Forms.NumericUpDown();<br />
            this.startAsyncButton = new System.Windows.Forms.Button();<br />
            this.cancelAsyncButton = new System.Windows.Forms.Button();<br />
            this.resultLabel = new System.Windows.Forms.Label();<br />
            this.progressBar1 = new System.Windows.Forms.ProgressBar();<br />
            this.backgroundWorker1 = new System.ComponentModel.BackgroundWorker();<br />
            ((System.ComponentModel.ISupportInitialize)(this.numericUpDown1)).BeginInit();<br />
            this.SuspendLayout();<br />
            // <br />
            // numericUpDown1<br />
            // <br />
            this.numericUpDown1.Location = new System.Drawing.Point(16, 16);<br />
            this.numericUpDown1.Maximum = new System.Decimal(new int[] {<br />
            91,<br />
            0,<br />
            0,<br />
            0});<br />
            this.numericUpDown1.Minimum = new System.Decimal(new int[] {<br />
            1,<br />
            0,<br />
            0,<br />
            0});<br />
            this.numericUpDown1.Name = "numericUpDown1";<br />
            this.numericUpDown1.Size = new System.Drawing.Size(80, 20);<br />
            this.numericUpDown1.TabIndex = 0;<br />
            this.numericUpDown1.Value = new System.Decimal(new int[] {<br />
            1,<br />
            0,<br />
            0,<br />
            0});<br />
            // <br />
            // startAsyncButton<br />
            // <br />
            this.startAsyncButton.Location = new System.Drawing.Point(16, 72);<br />
            this.startAsyncButton.Name = "startAsyncButton";<br />
            this.startAsyncButton.Size = new System.Drawing.Size(120, 23);<br />
            this.startAsyncButton.TabIndex = 1;<br />
            this.startAsyncButton.Text = "Start Async";<br />
            this.startAsyncButton.Click += new System.EventHandler(this.startAsyncButton_Click);<br />
            // <br />
            // cancelAsyncButton<br />
            // <br />
            this.cancelAsyncButton.Enabled = false;<br />
            this.cancelAsyncButton.Location = new System.Drawing.Point(153, 72);<br />
            this.cancelAsyncButton.Name = "cancelAsyncButton";<br />
            this.cancelAsyncButton.Size = new System.Drawing.Size(119, 23);<br />
            this.cancelAsyncButton.TabIndex = 2;<br />
            this.cancelAsyncButton.Text = "Cancel Async";<br />
            this.cancelAsyncButton.Click += new System.EventHandler(this.cancelAsyncButton_Click);<br />
            // <br />
            // resultLabel<br />
            // <br />
            this.resultLabel.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D;<br />
            this.resultLabel.Location = new System.Drawing.Point(112, 16);<br />
            this.resultLabel.Name = "resultLabel";<br />
            this.resultLabel.Size = new System.Drawing.Size(160, 23);<br />
            this.resultLabel.TabIndex = 3;<br />
            this.resultLabel.Text = "(no result)";<br />
            this.resultLabel.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;<br />
            // <br />
            // progressBar1<br />
            // <br />
            this.progressBar1.Location = new System.Drawing.Point(18, 48);<br />
            this.progressBar1.Name = "progressBar1";<br />
            this.progressBar1.Size = new System.Drawing.Size(256, 8);<br />
            this.progressBar1.Step = 2;<br />
            this.progressBar1.TabIndex = 4;<br />
            // <br />
            // backgroundWorker1<br />
            // <br />
            this.backgroundWorker1.WorkerReportsProgress = true;<br />
            this.backgroundWorker1.WorkerSupportsCancellation = true;<br />
            // <br />
            // FibonacciForm<br />
            // <br />
            this.ClientSize = new System.Drawing.Size(292, 118);<br />
            this.Controls.Add(this.progressBar1);<br />
            this.Controls.Add(this.resultLabel);<br />
            this.Controls.Add(this.cancelAsyncButton);<br />
            this.Controls.Add(this.startAsyncButton);<br />
            this.Controls.Add(this.numericUpDown1);<br />
            this.Name = "FibonacciForm";<br />
            this.Text = "Fibonacci Calculator";<br />
            ((System.ComponentModel.ISupportInitialize)(this.numericUpDown1)).EndInit();<br />
            this.ResumeLayout(false);<br />
<br />
        }<br />
		#endregion<br />
<br />
        [STAThread]<br />
        static void Main()<br />
        {<br />
            Application.Run(new FibonacciForm());<br />
        }<br />
    }<br />
}

GeneralRe: backgroundworker Pin
Yustme6-Nov-06 5:11
Yustme6-Nov-06 5:11 
AnswerRe: backgroundworker Pin
Eric Dahlvang6-Nov-06 5:09
Eric Dahlvang6-Nov-06 5:09 
GeneralRe: backgroundworker Pin
Yustme6-Nov-06 10:12
Yustme6-Nov-06 10:12 
AnswerRe: backgroundworker Pin
mertkan656-Nov-06 20:46
mertkan656-Nov-06 20:46 
QuestionTravelling Salesman Problem Pin
and_reas5-Nov-06 23:14
and_reas5-Nov-06 23:14 
AnswerRe: Travelling Salesman Problem Pin
ednrgc6-Nov-06 3:52
ednrgc6-Nov-06 3:52 
AnswerCross poster not doing their own homework Pin
leckey6-Nov-06 6:44
leckey6-Nov-06 6:44 
Questionparallel cellular automata Pin
MozhdehQeraati5-Nov-06 22:54
MozhdehQeraati5-Nov-06 22:54 
QuestionExam 70–536: TS: Microsoft .NET Framework 2.0 - Application Development Foundation, Dumps? Pin
kumar.bs5-Nov-06 22:46
kumar.bs5-Nov-06 22:46 
AnswerRe: Exam 70–536: TS: Microsoft .NET Framework 2.0 - Application Development Foundation, Dumps? Pin
Tarakeshwar Reddy5-Nov-06 23:28
professionalTarakeshwar Reddy5-Nov-06 23:28 
GeneralRe: Exam 70–536: TS: Microsoft .NET Framework 2.0 - Application Development Foundation, Dumps? Pin
kumar.bs5-Nov-06 23:32
kumar.bs5-Nov-06 23:32 
AnswerRe: Exam 70–536: TS: Microsoft .NET Framework 2.0 - Application Development Foundation, Dumps? Pin
Rahithi6-Nov-06 4:21
Rahithi6-Nov-06 4:21 
QuestionDrag and drop in embedded usercontrol Pin
mesmer5-Nov-06 22:32
mesmer5-Nov-06 22:32 
Questionchanging attribute value of a property outside the class . Pin
praveenqwe5-Nov-06 22:04
praveenqwe5-Nov-06 22:04 
AnswerRe: changing attribute value of a property outside the class . Pin
quiteSmart5-Nov-06 22:36
quiteSmart5-Nov-06 22:36 
GeneralRe: changing attribute value of a property outside the class . Pin
praveenqwe5-Nov-06 22:53
praveenqwe5-Nov-06 22:53 
AnswerRe: changing attribute value of a property outside the class . Pin
Amar Chaudhary5-Nov-06 23:08
Amar Chaudhary5-Nov-06 23:08 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.