Can't Invoke from System.Threading.Timer

  • Thread starter Thread starter Zlajoni
  • Start date Start date
Z

Zlajoni

Can anybody tell me why I can't compile this simple piece of code? I
can use Invoke when dealing with Forms.Timer with no problems, but I
just can't get it to work with System.Threading.Timer.

using System;
using System.Drawing;
using System.Collections;
using System.Windows.Forms;
using System.Data;
using System.Threading;

namespace ThreadTimerTest
{
public class Form1 : System.Windows.Forms.Form
{
private System.Threading.Timer ThreadTimer;
private System.Windows.Forms.ListBox listBox1;

public Form1()
{
InitializeComponent();

// Create the delegate that invokes methods for the timer.
TimerCallback timerDelegate = new TimerCallback(CheckStatus);

// Create a timer that waits one second, then invokes every second.
ThreadTimer = new System.Threading.Timer
(timerDelegate,null,5000,10000);

}

protected override void Dispose( bool disposing )
{
base.Dispose( disposing );
}

#region Windows Form Designer generated code

private void InitializeComponent()
{
this.listBox1 = new System.Windows.Forms.ListBox();
//
// listBox1
//
this.listBox1.Location = new System.Drawing.Point(184, 40);
this.listBox1.Size = new System.Drawing.Size(248, 353);
//
// Form1
//
this.ClientSize = new System.Drawing.Size(482, 432);
this.Controls.Add(this.listBox1);
this.Text = "Form1";

}
#endregion

static void Main()
{
Application.Run(new Form1());
}

static void CheckStatus(object state)
{
this.Invoke(new EventHandler(SetText));
}

private void SetText(object o, EventArgs e)
{
listBox1.Items.Insert(0,"Hello");
}

}
}


Thanks in advance!
Zlatan
 
Haven't tried your code, but what happens if you make CheckStatus not
static?

Cheers
Daniel
 
Here are the errors the compiler returns:
Keyword this is not valid in a static property, static method, or static
field initializer - Meaning you can't use "this" in the CheckStatus() method
since it's static
An object reference is required for the nonstatic field, method, or property
'ThreadTimerTest.Form1.SetText(object, System.EventArgs)'

If you remove the static it should work as Daniel said. You can also make a
static reference to your form (so you can call Invoke) and make SetText
static which should also work but I don't see the point in that.
 
Back
Top