Threading C#
Hi,
I am a beginner to .Net Compact Framework programming, I am developing a windows mobile 6 application and need some help with Threading.
My Question:, is How to start a Timer on a a form when a form is instanciated and run on a separate thread and also be able to stop the thread when the form is not in use. Since .Net Compact Framework is limited to a certain extent.
Any Help will be greatly appreciated. Thanks.
Asad ButtPosted Sep 11, 2009, 7:23 AM
per your requiremnt. Atleast the timer 'formTimer 'starts and ends the way you want
Hope it helps
using System;
using System.Linq;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Threading;
namespace SmartDeviceProject1
{
public partial class Form1 : Form
{
static int timeChk = 0;
Thread thread;
System.Windows.Forms.Timer formTimer;
public Form1()
{
InitializeComponent();
// start Thread
thread = new Thread(new ThreadStart(EnableTimer));
thread.Start();
// This is d is notan extra timer and is not threaded
// you may replace this with what you need to do
formTimer = new System.Windows.Forms.Timer();
formTimer.Interval = 1000;
formTimer.Tick += new EventHandler(formTimer_Tick);
formTimer.Enabled = true;
}
void formTimer_Tick(object sender, EventArgs e)
{
label1.Text = "Timer count : " + timeChk.ToString();
}
//
static void EnableTimer()
{
// calls method timeCheck which increaments variable timeChk
TimerCallback timeCB = new TimerCallback(timeCheck);
System.Threading.Timer t = new System.Threading.Timer(
timeCB, // The TimerCallback delegate type.
" ", // Any info to pass into the called method.
0, // Amount of time to wait before starting.
1000);
}
static void timeCheck(Object state)
{
timeChk++;
}
private void button1_Click(object sender, EventArgs e)
{
// dispose the timer here or may dipose it
// int Form_Closing event.
formTimer.Dispose();
MessageBox.Show("Timer count at closing: " + timeChk.ToString() +"\n\nThis Form will now close ");
this.Dispose();
}
}
}