C# Timer to flash a label on button click

December 4, 2012 at 14:03:13
Specs: XP\7
I have a button that when it is pressed I want to start a timer that flashes a label while the rest of the button1 click event is proccessed. I have read that a timer works on it's own thread so I should be able to run both threads asynchronly. As of now the label flashes as expected but it doesn't start unting all of the button 1 click is finished. How can I make this work at the same time. I am a newbie so please help.

Here 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.Diagnostics;
using System.Data.SqlClient;
using System.IO;
using System.Windows.Forms;
using System.Threading;


namespace WindowsFormsApplication3
{
public partial class Form1 : Form
{

public Form1()
{
InitializeComponent();


}


private void Form1_Load(object sender, EventArgs e)
{

}

private void button1_Click(object sender, EventArgs e)
{
timer1.Start();
//do other stuff
}

private void timer1_Tick(object sender, EventArgs e)
{
TransferStatusLabel1.Visible = !TransferStatusLabel1.Visible;
}

}
}


See More: C# Timer to flash a label on button click

Report •


#1
December 4, 2012 at 22:27:25
There are four timers in .NET.

System.Windows.Forms.Timer - This works though the message pump. It only works on a GUI thread, and it only fires when you're pumping messages. In a single threaded application, this means it'll only fire if your application is idle. The Win32 method it wraps dates back to Win16, so it lacks alternate threads. As it isn't concurrent, you shouldn't run into any concurrency issues.

System.Timers.Timer - Runs from the ThreadPool, and does its work from there. It has thread safety baked in, so if you're careful you shouldn't have too many concurrency issues.

System.Threading.Timer - The underpinnings of Timers.Timer, but without thread safety. You don't want it.

System.Windows.Threading.DispatcherTimer - WPF, so you don't want it and can't use it.

I'm not sure if you have a Forms.Timer, or a Timers.Timer, but I suspect it's the Forms version. What I would probably do in your position is to use a Forms timer for your button flashing. For the actual work, I'd throw a System.ComponentModel.BackgroundWorker at it.

How To Ask Questions The Smart Way


Report •
Related Solutions


Ask Question