CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 7 of 7
  1. #1
    Join Date
    Dec 2010
    Posts
    8

    BackgroundWorker & timer

    Hi,
    I'm a newbie and I'd like some help please.
    I created a small applications which check CPU usage on a list of servers every 5000 timer intervals.
    The application was working but not responsive when the CPU usage is being fetched.
    Now, I'm trying to use BackgroundWorker as well as the timer.
    How can I do that?
    Do I call my timer1_Tick event from within ackgroundWorker1_DoWork ?

    Thanks for your help.
    W.

  2. #2
    Arjay's Avatar
    Arjay is offline Moderator / EX MS MVP Power Poster
    Join Date
    Aug 2004
    Posts
    13,490

    Re: BackgroundWorker & timer

    You need to use the Timer from the Threading namespace (as opposed to the timer in the Forms namespace).

  3. #3
    Join Date
    Dec 2010
    Posts
    8

    Re: BackgroundWorker & timer

    How do I do that?
    Do you mean I need to create a timer programatically in my ackgroundWorker1_DoWork event?
    Could you please give me some more pointers.
    Thanks in advance.

  4. #4
    Join Date
    May 2007
    Location
    Denmark
    Posts
    623

    Re: BackgroundWorker & timer

    I would do something like this:

    1. Create a timer that runs every x miliseconds, say 5000.
    2. When the timer fires, create a thread or backgroundworker and fetch the CPU usage from there.

    Just seems like the obvious way of doing it to me
    It's not a bug, it's a feature!

  5. #5
    Join Date
    Dec 2010
    Posts
    8

    Re: BackgroundWorker & timer

    Hi,
    I wrote some code which it'll do what I want to achieve.
    The only problem is that when I close my form while the thread is running it throws an error in Dispose:
    "Cross-thread operation not valid: Control 'label2' accessed from a thread other than the thread it was created on."
    This error is thrown only when WaistTime function is running and the labels are being updated.

    How do I fix this error?
    I don't want to add a cancel button. I'd like to able to close my application whenever I want to.
    Thanks,
    w.

    This is my code:


    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Data;
    using System.Drawing;
    using System.Linq;
    using System.Text;
    using System.Windows.Forms;

    namespace nzBackGroundWorkerr
    {
    public partial class Form1 : Form
    {
    public Form1()
    {
    InitializeComponent();
    }



    private void timer1_Tick(object sender, EventArgs e)
    {
    timer1.Stop();

    // StartOur Thread
    backgroundWorker1.RunWorkerAsync("Test");

    }

    private void WaistTime()
    {
    for (int i = 0; i < 100; i++)
    {
    for (int i2 = 0; i2 < 10; i2++)
    {
    backgroundWorker1.ReportProgress(i2, label2.Text);
    }
    backgroundWorker1.ReportProgress(i, label1.Text);

    }
    }

    private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
    {
    WaistTime();
    }

    private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
    {
    timer1.Start();
    label1.Text = "Finished!";
    label2.Text = "Finished too!";
    }

    private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
    {
    label1.Text = e.ProgressPercentage.ToString();
    label2.Text = e.ProgressPercentage.ToString();
    }

    private void btnStartTimer_Click(object sender, EventArgs e)
    {
    timer1.Enabled = true;
    }
    }
    }


    //=-=-=-=-=-=-==-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
    namespace nzBackGroundWorkerr
    {
    partial class Form1
    {
    /// <summary>
    /// Required designer variable.
    /// </summary>
    private System.ComponentModel.IContainer components = null;

    /// <summary>
    /// Clean up any resources being used.
    /// </summary>
    /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
    protected override void Dispose(bool disposing)
    {
    if (disposing && (components != null))
    {
    components.Dispose();
    }
    base.Dispose(disposing);
    }

    #region Windows Form Designer generated code

    /// <summary>
    /// Required method for Designer support - do not modify
    /// the contents of this method with the code editor.
    /// </summary>
    private void InitializeComponent()
    {
    this.components = new System.ComponentModel.Container();
    this.btnStartTimer = new System.Windows.Forms.Button();
    this.label1 = new System.Windows.Forms.Label();
    this.backgroundWorker1 = new System.ComponentModel.BackgroundWorker();
    this.timer1 = new System.Windows.Forms.Timer(this.components);
    this.label2 = new System.Windows.Forms.Label();
    this.SuspendLayout();
    //
    // btnStartTimer
    //
    this.btnStartTimer.Location = new System.Drawing.Point(205, 197);
    this.btnStartTimer.Name = "btnStartTimer";
    this.btnStartTimer.Size = new System.Drawing.Size(75, 23);
    this.btnStartTimer.TabIndex = 2;
    this.btnStartTimer.Text = "StartTimer";
    this.btnStartTimer.UseVisualStyleBackColor = true;
    this.btnStartTimer.Click += new System.EventHandler(this.btnStartTimer_Click);
    //
    // label1
    //
    this.label1.AutoSize = true;
    this.label1.Location = new System.Drawing.Point(226, 18);
    this.label1.Name = "label1";
    this.label1.Size = new System.Drawing.Size(35, 13);
    this.label1.TabIndex = 3;
    this.label1.Text = "label1";
    //
    // backgroundWorker1
    //
    this.backgroundWorker1.WorkerReportsProgress = true;
    this.backgroundWorker1.WorkerSupportsCancellation = true;
    this.backgroundWorker1.DoWork += new System.ComponentModel.DoWorkEventHandler(this.backgroundWorker1_DoWork);
    this.backgroundWorker1.RunWorkerCompleted += new System.ComponentModel.RunWorkerCompletedEventHandler(this.backgroundWorker1_RunWorkerCompleted);
    this.backgroundWorker1.ProgressChanged += new System.ComponentModel.ProgressChangedEventHandler(this.backgroundWorker1_ProgressChanged);
    //
    // timer1
    //
    this.timer1.Interval = 3000;
    this.timer1.Tick += new System.EventHandler(this.timer1_Tick);
    //
    // label2
    //
    this.label2.AutoSize = true;
    this.label2.Location = new System.Drawing.Point(226, 41);
    this.label2.Name = "label2";
    this.label2.Size = new System.Drawing.Size(35, 13);
    this.label2.TabIndex = 4;
    this.label2.Text = "label2";
    //
    // Form1
    //
    this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
    this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
    this.ClientSize = new System.Drawing.Size(292, 266);
    this.Controls.Add(this.label2);
    this.Controls.Add(this.label1);
    this.Controls.Add(this.btnStartTimer);
    this.Name = "Form1";
    this.Text = "Form1";
    this.ResumeLayout(false);
    this.PerformLayout();

    }

    #endregion

    private System.Windows.Forms.Button btnStartTimer;
    private System.Windows.Forms.Label label1;
    private System.ComponentModel.BackgroundWorker backgroundWorker1;
    private System.Windows.Forms.Timer timer1;
    private System.Windows.Forms.Label label2;
    }
    }

  6. #6
    Arjay's Avatar
    Arjay is offline Moderator / EX MS MVP Power Poster
    Join Date
    Aug 2004
    Posts
    13,490

  7. #7
    Join Date
    Nov 2010
    Posts
    34

    Re: BackgroundWorker & timer

    Very similar to this, then function(args, args etc);

    delegate void PassRT(string line, int num);
    public void RT1(string line, int num)
    {
    if (richTextBox1.InvokeRequired)
    {
    PassRT x = new PassRT(RT1);
    richTextBox1.Invoke(x, new object[] { line, num });
    }
    else
    {
    if (num == 1)
    {
    richTextBox1.Text = richTextBox1.Text + "\n" + line;
    richTextBox1.SelectionStart = richTextBox1.Text.Length;
    richTextBox1.ScrollToCaret();
    }
    else
    {
    richTextBox1.Text = richTextBox1.Text + line;
    richTextBox1.SelectionStart = richTextBox1.Text.Length;
    richTextBox1.ScrollToCaret();
    }
    }
    }

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured