Dispatcher timer is firing twice :( - c#

i have problems with this timer, my function in the Tick event are appearing twice.. i want it to appear only once..
public void timerStart()
{
DispatcherTimer updaterTimer = new DispatcherTimer();
updaterTimer.Tick += new EventHandler(updaterTimer_Tick);
updaterTimer.Interval = new TimeSpan(0,0,0,0,300);
updaterTimer.Start();
}
private void updaterTimer_Tick(object sender, EventArgs e)
{
updaterTimer.Stop();
checkSigningAvailable();
updaterTimer.Start();
}
This is the method that is checked every tick of the timer,
public void checkSigningAvailable()
{
if (dt_signing_in.CompareTo(DateTime.Now) < 0)
{
if (!InPopAlready)
{
InPopAlready = true;
disableSigningIn("False", this.event_id);
}
}
}
And the messagebox in the bottom is appearing twice after calling this function above
public void disableSigningIn(string Out,string event_id)
{
System.Console.WriteLine("POPED "+ InPopAlready);
connection.Open();
string sign = "True," + Out;
string query = "update data_storage set data_details = '" + sign + "' where data_name = 'Signing';";
NpgsqlCommand command = new NpgsqlCommand(query, connection);
command.ExecuteNonQuery();
connection.Close();
sign_in.Content = "Sign-in Time : Over";
string query2 = concatQuery(getIDnumberAttendance(event_id));
updateAbsences(query2);
MessageBox.Show("Signing in is over!", "No more signing in!", MessageBoxButton.OK, MessageBoxImage.Information);
}

You are adding " += new EventHandler " and adding and adding new EventHandlers all over new EventHandlers but never remove them..
All the previous one gets fired each Time the Timer Starts again.
You can reproduce this behaviour if you implement a counter, then you will see that is doubles with each new added and raised Event.
(Edit: Just was confused because the "new" keyword, but actually I will not delete the answer since I am pretty sure that in some cases it will exactly be the issue)
The following may help:
How to remove all event handlers from an event
And here the most easy solution:
(You may polish it by using delegates)
Declaration in Class:
private System.Windows.Threading.DispatcherTimer P5DispatcherHelpsystemTimer = new System.Windows.Threading.DispatcherTimer();
private EventHandler P5DispatcherTimerHandler;
Dispatcher Timer Method:
private void InitializeHelpsystemCronjobs(System.Windows.Controls.Canvas sub_CanvasElement)
{
P5DispatcherTimerHandler = (sender, e) => P5DispatcherHelpsystemTimerTick(sender, e, sub_CanvasElement);
P5DispatcherHelpsystemTimer.Tick += P5DispatcherTimerHandler;
P5DispatcherHelpsystemTimer.Interval = new TimeSpan(0, 0, 1);
P5DispatcherHelpsystemTimer.Start();
}
Dispatcher TimerTick Method:
private void P5DispatcherHelpsystemTimerTick(object sender, EventArgs e, System.Windows.Controls.Canvas sub_CanvasElement)
{
P5DispatcherHelpsystemTimer.Stop();
{
// Do stuff
}
P5DispatcherHelpsystemTimer.Start();
}
// Somewhere when an Trigger Event or Action etc. happens and the Timer shall start:
InitializeHelpsystemCronjobs(HelpsystemHelpCanvas);
// Somewhere when it sahll stop:
P5DispatcherHelpsystemTimer.Stop();
P5DispatcherHelpsystemTimer.Tick -= P5DispatcherTimerHandler;
(If you have more complex situation you definitely need delegate List<>)

For me, it was not starting, stopping or the Timer at all. It was the DI/IOC container resolving two instances of the ViewModel which started a new refresh timer in the constructor. Check to make sure that you are always seeing the same ViewModel instance and not actually two separate ones, firing two separate Timers.

The code below fires the MessageBox only once:
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
this.timerStart();
}
DispatcherTimer updaterTimer;
private bool InPopAlready;
DateTime dt_signing_in;
public void timerStart()
{
updaterTimer = new DispatcherTimer();
updaterTimer.Tick += new EventHandler(updaterTimer_Tick);
updaterTimer.Interval = new TimeSpan(0, 0, 0, 0, 300);
updaterTimer.Start();
}
private void updaterTimer_Tick(object sender, EventArgs e)
{
updaterTimer.Stop();
checkSigningAvailable();
updaterTimer.Start();
}
public void checkSigningAvailable()
{
if (dt_signing_in.CompareTo(DateTime.Now) < 0)
{
if (!InPopAlready)
{
InPopAlready = true;
// Calling your method and showing MessageBox
MessageBox.Show("Signing in is over!", "No more signing in!", MessageBoxButton.OK, MessageBoxImage.Information);
}
}
}
}

I tend to write my "once-off" timer code like this:
var updaterTimer = new DispatcherTimer();
updaterTimer.Interval = new TimeSpan(0, 0, 0, 0, 300);
EventHandler tick = null;
tick = (s, e) =>
{
updaterTimer.Stop();
updaterTimer.Tick -= tick;
/* execute once-off code here */
};
updaterTimer.Tick += tick;
updaterTimer.Start();
Then I don't need to fluff with making new methods - it's all in one local code block.

Related

How to check every 30seconds with dispatchertimer without affect the UI in c#?

I hav tried the below code for checking reports from server in every 30seconds,but after 30seconds tick,The application hangs for several seconds.How to avoid the Hanging problem.
The below code am tried,what change want to given in this?
System.Windows.Threading.DispatcherTimer dispatcherTimer2 = new System.Windows.Threading.DispatcherTimer();
dispatcherTimer2.Tick += new EventHandler(dispatcherTimer2_Tick);
dispatcherTimer2.Interval = new TimeSpan(0, 0, 30);
Public void dispatcherTimer2_Tick(object sender, EventArgs e)
{
dispatcherTimer2.start();
//code for function call autoreport();
}
DispatcherTimer callback is executed on main UI thread and blocks it.
Use System.Threading.Timer and if you need to update user interface from timer callback use one of
Dispatcher.Invoke
overloads.
In code something like this
public partial class MainWindow : Window
{
System.Threading.Timer timer;
public MainWindow()
{
InitializeComponent();
timer = new System.Threading.Timer(OnCallBack, null, 0, 30 * 1000);
}
private void OnCallBack(object state)
{
//code to check report
Dispatcher.Invoke(() =>
{
//code to update ui
this.Label.Content = string.Format("Fired at {0}", DateTime.Now);
});
}
}
var timer = new System.Threading.Timer(
delegate
{
//--update functions here (large operations)
var value = Environment.TickCount;
//--run update using interface thread(UI Thread)
//--for WinForms
Invoke(
new Action(() =>
{
//--set the value to UI Element
}));
//--for WPF
Dispatcher.Invoke(
new Action(() =>
{
//--set the value to UI Element
}), null);
});
var period = TimeSpan.FromSeconds(30);
timer.Change(period, period);
I hope it helps.
This is worked for me
public Form1()
{
InitializeComponent();
var timer = new System.Timers.Timer(500);
// Hook up the Elapsed event for the timer.
timer.Elapsed += timer_Elapsed;
timer.Enabled = true;
}
void timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
{
Invoke(
new Action(() =>
{
label1.Text += "Test Label";
Application.DoEvents();
}));
}

C# Timer Event not firing off

I can't get the timer to tick every time when i create a new command object I am wondering what is causing this. I am new to C# so if i could get help as to why this is happening it would be greatly appreciated.
This should trigger, but doesnt
command Cmd = new command("!example", 10);
Here's the code.
public class Timeout
{
public Timeout() { }
public static List<command> timeouts = new List<command>();
public class command
{
public string cmd;
public int seconds;
private System.Windows.Forms.Timer timer = new System.Windows.Forms.Timer() { Interval = 1000 };
public command(string cmd, int seconds)
{
Debug.WriteLine("created, " + cmd + ", " + seconds);
this.cmd = cmd;
this.seconds = seconds;
this.timer.Tick += new EventHandler(Timer_Tick);
timer.Start();
}
private void Timer_Tick(object sender, EventArgs e)
{
Debug.WriteLine("tick -> " + seconds);
if (seconds > 0)
seconds--;
else
{
timer.Tick -= Timer_Tick;
timeouts.Remove(this);
Debug.WriteLine("removed");
}
}
}
}
actually you can do this way.
call the timer once you create the object
command cmd =new command("!example",10);
//then am calling the timer event
timer = new Timer(3000); // Set up the timer for 3 seconds
timer.Elapsed += new ElapsedEventHandler(timerElapsed);
//_timer_Elapsed is the event name
timer.Enabled = true;
public static void timerElapsed(object sender, ElapsedEventArgs e)
{
//do something here
}
please find the link here for more reference.hope my comment helps you :)

How to stop timer affacted by button click?

i am working on a winform application in which i have a timer.it is being used for showing stopwatch on the form. When i fire a button than my timer is interrupted. i want my timer to be uninterrupted while button is clicked. My code is as followed:-
private void button1_Click(object sender, EventArgs e)
{
if (!_timerRunning)
{
// Set the start time to Now
_startTime = DateTime.Now;
// Store the total elapsed time so far
_totalElapsedTime = _currentElapsedTime;
_timer.Start();
_timerRunning = true;
}
SqlConnection Con = new SqlConnection("Data Source=69.162.83.242,1232;Initial Catalog=test1;Uid=test;pwd=1234#Test;MultipleActiveResultSets=true;Connect TimeOut=60000;");
//SqlConnection Con = new SqlConnection("Data Source=ADMIN-PC\\YASH;Initial Catalog=test;Integrated Security=True; Connect TimeOut=600");
Con.Open();
string messageMask = "{0} # {1} : {2}";
string message = string.Format(messageMask, label6.Text, DateTime.Now.ToShortTimeString(), richTextBox2.Text);
richTextBox1.AppendText(Environment.NewLine + message);
SqlCommand cmd, cmd1;
cmd = new SqlCommand("Update Chat set UserInitial=#message,Updated=1 where ExpertName ='" + label6.Text + "'", Con);
cmd.Parameters.AddWithValue("#message", message);
cmd.ExecuteNonQuery();
Con.Close();
richTextBox2.Text = String.Empty;
richTextBox1.ScrollToCaret();
}
private void timer1_Tick(object sender, EventArgs e)
{
richTextBox1.ScrollToCaret();
count = count + 1;
count1 = count1 + 1;
timerSinceStartTime = new TimeSpan(timerSinceStartTime.Hours, timerSinceStartTime.Minutes, timerSinceStartTime.Seconds + 1);
// The current elapsed time is the time since the start button was
// clicked, plus the total time elapsed since the last reset
_currentElapsedTime = timerSinceStartTime + _totalElapsedTime;
// These are just two Label controls which display the current
// elapsed time and total elapsed time
if (count1 == 180)
{
MessageBox.Show("You are Automaticlly hired by User");
if (label7.Visible == true)
{
label7.Visible = false;
count = 0;
timerSinceStartTime = new TimeSpan(00, 00, 00);
label3.Visible = true;
}
}
label3.Text = timerSinceStartTime.ToString();
// If we're running on the UI thread, we'll get here, and can safely update
// the label's text.
richTextBox1.ScrollToCaret();
}
how to solve it??
thanks in Advance
Your problem stems from the fact you're using System.Windows.Forms.Timer which is not threaded and relies on the message pump. While your program is busy in the UI thread the message pump won't be processed.
You can improve this by moving to a timer that supports threads. I prefer System.Timers.Timer but there's also System.Threading.Timer.
With System.Timers.Timer the tick event is raised on a background thread if you don't pass any sync object in so that any code within the event handler will be handled in a separate thread.
Of course, to update the form we have to marshal back to the UI thread so we'll also need to use Control.Invoke().
This is very rough, but something like this:
System.Timers.Timer timer = new System.Timers.Timer();
timer.Elapsed += new ElapsedEventHandler(OnTimer);
timer.Interval = 1000;
timer.AutoReset = false;
timer.Enabled = true;
public void OnTimer(object sender, ElapsedEventArgs e)
{
// Do something busy like dancing
// Update form
Invoke((MethodInvoker)delegate() {
UpdateForm();
});
// Restart timer
((System.Timers.Timer)sender).Start();
}
public void UpdateForm()
{
// Code to update the form
}
Note I use AutoReset = false so that if the tick event takes longer than the timer interval you won't get overlap. You may or may not want this it entirely depends on what you're doing.
You can try this,
private bool bStopTimer = true;
private void StartTimer()
{
System.Threading.Thread thread = new System.Threading.Thread(new System.Threading.ThreadStart(this.ThreadTimer));
thread.IsBackground = true;
thread.Start();
}
private void ThreadTimer()
{
while (bStopTimer)
{
System.Threading.Thread.Sleep(1000); //interval in millisecond
lock(lblLabel.Text)
{
lblLable.Text = System.DateTime.Now.ToString("HH:mm:ss");
}
}
}
Update
place this line before Application.Run(new frmForm);
System.Windows.Forms.Control.CheckForIllegalCrossThreadCalls = false;

Call the click event of a button after timer elapses

I am trying to create a form that queries a database. The form has a "Query" button and I would like the query to run every 30 seconds automatically as well. However, when I try to do it I get an error saying an object reference is needed for QueryBtn since it is non-static.
However, due to the nature of the form I can't change the QueryBtn to static without causing other problems. How can I call on the action of QueryBtn_Click every 30 seconds?
namespace ModalityWorklistSCU
{
public partial class ModalityWorklistSCUExampleForm : Form
{
// Here's the 30 second timer
private static System.Timers.Timer myTimer;
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
myTimer = new System.Timers.Timer();
myTimer.Elapsed += new ElapsedEventHandler(OnTimedEvent);
myTimer.Interval = 30000;
myTimer.Enabled = true;
Application.Run(new ModalityWorklistSCUExampleForm());
}
// This is the form
public ModalityWorklistSCUExampleForm()
{
InitializeComponent();
}
// This defines what happens when the timer elapses. I am trying to call the click event of another button.
private static void OnTimedEvent(object source, ElapsedEventArgs e)
{
QueryBtn.PerformClick();
}
// This is a snipet of the event I want to call every 5 seconds:
private void QueryBtn_Click(object sender, EventArgs e)
{
DCXOBJIterator it = null;
DCXREQ req = null;
DCXOBJ rp = null;
DCXOBJ sps = null;
DCXELM el = null;
DCXOBJIterator spsIt = null;
try
{
// Fill the query object
rp = new DCXOBJ();
sps = new DCXOBJ();
el = new DCXELM();
// Build the Scheduled procedure Step (SPS) item
el.Init((int)DICOM_TAGS_ENUM.ScheduledStationAETitle);
el.Value = StationNameEdit.Text;
sps.insertElement(el);
Thanks
Refactor your code to pull logic out of your event handler.
private void QueryBtn_Click(object sender, EventArgs e)
{
NewMethod();
}
private static void OnTimedEvent(object source, ElapsedEventArgs e)
{
NewMethod();
}
private void NewMethod()
{
DCXOBJIterator it = null;
DCXREQ req = null;
DCXOBJ rp = null;
DCXOBJ sps = null;
DCXELM el = null;
DCXOBJIterator spsIt = null;
try
{
// Fill the query object
rp = new DCXOBJ();
sps = new DCXOBJ();
el = new DCXELM();
// Build the Scheduled procedure Step (SPS) item
el.Init((int)DICOM_TAGS_ENUM.ScheduledStationAETitle);
el.Value = StationNameEdit.Text;
sps.insertElement(el);
}
}
Instead of System.Timers.Timer try to use System.Windows.Forms.Timer.
Here is some info on it:
http://msdn.microsoft.com/en-us/library/system.windows.forms.timer(v=vs.110).aspx
Draw the timer element on the form straight from the form designer, add event handler for Tick event and execute your logic there. You should move all your logic to separate function and call it from button Click event and Timer event.
You can also call button click event handler directly just as any method just passing needed arguments, but as paqogomez correctly pointed out, this is not considered as good practice.
QueryBtn_Click(this, EventArgs.Empty).

timer in thread problem

I have my application in which in three datagridview independently in three thread load data from wcf service. I execute in each thread timer which every second load this data.
My problem is that every time my thread go threw each thread but only like I show in method timerNowyYork_Elapsed
Any idea why this happens ? I bad lock thread?
this code :
using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;
using System.Threading;
namespace Sprawdzanie_warunków_pogodowych
{
public partial class Form1 : Form
{
PogodaEntities entity = new PogodaEntities();
System.Timers.Timer timerKrakow = new System.Timers.Timer();
System.Timers.Timer timerSzczecin = new System.Timers.Timer();
System.Timers.Timer timerNowyYork = new System.Timers.Timer();
KeyValuePair<string, string> krakowInfo;
KeyValuePair<string, string> szczecinInfo;
KeyValuePair<string, string> nowyYorkInfo;
public Form1()
{
System.Net.ServicePointManager.Expect100Continue = false;
InitializeComponent();
List<MiastoContainer> miasta = (from miasto in entity.Miasta
select new MiastoContainer()
{
MiastoName = miasto.Nazwa,
Panstwo = miasto.Państwo
}).ToList();
krakowInfo = new KeyValuePair<string, string>(miasta[0].MiastoName, miasta[0].Panstwo);
szczecinInfo = new KeyValuePair<string, string>(miasta[1].MiastoName, miasta[1].Panstwo);
nowyYorkInfo = new KeyValuePair<string, string>(miasta[2].MiastoName, miasta[2].Panstwo);
ParameterizedThreadStart ptsKrakow = new ParameterizedThreadStart(PobierzKrakow);
Thread tKrakow = new Thread(ptsKrakow);
tKrakow.Start(this.dataGridViewKrakow);
ParameterizedThreadStart ptsSzczecin = new ParameterizedThreadStart(PobierzSzczecin);
Thread tSzczecin = new Thread(ptsSzczecin);
tSzczecin.Start(this.dataGridViewSzczecin);
}
private void oAutorzeToolStripMenuItem_Click(object sender, EventArgs e)
{
new AboutBox1().Show();
}
private void zapiszRaportToolStripMenuItem_Click(object sender, EventArgs e)
{
}
public void PobierzKrakow(object parameters)
{
this.timerKrakow.Elapsed += new System.Timers.ElapsedEventHandler(timerKrakow_Elapsed);
this.timerKrakow.Enabled = true;
this.timerKrakow.Interval = 1000;
this.timerKrakow.Start();
}
public void PobierzSzczecin(object parameters)
{
this.timerSzczecin.Elapsed += new System.Timers.ElapsedEventHandler(timerSzczecin_Elapsed);
this.timerSzczecin.Enabled = true;
this.timerSzczecin.Interval = 1000;
this.timerSzczecin.Start();
}
public void PobierzNowyYork(object parameters)
{
this.timerNowyYork.Elapsed += new System.Timers.ElapsedEventHandler(timerNowyYork_Elapsed);
this.timerNowyYork.Enabled = true;
this.timerNowyYork.Interval = 1000;
this.timerNowyYork.Start();
}
void timerNowyYork_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
{ GlobalWeather.Weather weather = new GlobalWeather.Weather();
lock (weather)
{
//thread always start from here
List<object> weatherList = new List<object>();
weatherList.Add(weather.GetTempreature(nowyYorkInfo.Key, nowyYorkInfo.Value));
//and end here , never come any line further
weatherList.Add(weather.GetPressure(nowyYorkInfo.Key, nowyYorkInfo.Value));
weatherList.Add(weather.GetHumidity(nowyYorkInfo.Key, nowyYorkInfo.Value));
weatherList.Add(weather.GetVisibility(nowyYorkInfo.Key, nowyYorkInfo.Value));
entity.SaveChanges();
WarunkiPogodowe warunki = new WarunkiPogodowe()
{
Temperatura = weatherList[0].ToString(),
Ciśnienie = weatherList[1].ToString(),
Wilgotność = weatherList[2].ToString(),
Widoczność = weatherList[3].ToString(),
DataSprawdzenia = DateTime.Now
};
entity.AddToWarunkiPogodowe(warunki);
entity.SaveChanges();
int miastoId = entity.Miasta.First(m => m.Nazwa == nowyYorkInfo.Key).id;
Miasto_has_WarunkiPogodowe m_has_wp = new Miasto_has_WarunkiPogodowe()
{
idMiasto_FK = miastoId,
idWarunkiPogodowe_FK = warunki.id
};
entity.AddToMiasto_has_WarunkiPogodowe(m_has_wp);
entity.SaveChanges();
this.dataGridViewNowyYork.Rows.Add(warunki);
}
}
void timerSzczecin_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
{
GlobalWeather.Weather weather = new GlobalWeather.Weather();
lock (weather)
{
List<object> weatherList = new List<object>();
weatherList.Add(weather.GetTempreature(szczecinInfo.Key, szczecinInfo.Value));
weatherList.Add(weather.GetPressure(szczecinInfo.Key, szczecinInfo.Value));
weatherList.Add(weather.GetHumidity(szczecinInfo.Key, szczecinInfo.Value));
weatherList.Add(weather.GetVisibility(szczecinInfo.Key, szczecinInfo.Value));
entity.SaveChanges();
WarunkiPogodowe warunki = new WarunkiPogodowe()
{
Temperatura = weatherList[0].ToString(),
Ciśnienie = weatherList[1].ToString(),
Wilgotność = weatherList[2].ToString(),
Widoczność = weatherList[3].ToString(),
DataSprawdzenia = DateTime.Now
};
entity.AddToWarunkiPogodowe(warunki);
entity.SaveChanges();
int miastoId = entity.Miasta.First(m => m.Nazwa == szczecinInfo.Key).id;
Miasto_has_WarunkiPogodowe m_has_wp = new Miasto_has_WarunkiPogodowe()
{
idMiasto_FK = miastoId,
idWarunkiPogodowe_FK = warunki.id
};
entity.AddToMiasto_has_WarunkiPogodowe(m_has_wp);
entity.SaveChanges();
this.dataGridViewSzczecin.Rows.Add(warunki);
}
}
void timerKrakow_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
{
GlobalWeather.Weather weather = new GlobalWeather.Weather();
lock (weather)
{
List<object> weatherList = new List<object>();
weatherList.Add(weather.GetTempreature(krakowInfo.Key, krakowInfo.Value));
weatherList.Add(weather.GetPressure(krakowInfo.Key, krakowInfo.Value));
weatherList.Add(weather.GetHumidity(krakowInfo.Key, krakowInfo.Value));
weatherList.Add(weather.GetVisibility(krakowInfo.Key, krakowInfo.Value));
entity.SaveChanges();
WarunkiPogodowe warunki = new WarunkiPogodowe()
{
Temperatura = weatherList[0].ToString(),
Ciśnienie = weatherList[1].ToString(),
Wilgotność = weatherList[2].ToString(),
Widoczność = weatherList[3].ToString(),
DataSprawdzenia = DateTime.Now
};
entity.AddToWarunkiPogodowe(warunki);
entity.SaveChanges();
int miastoId = entity.Miasta.First(m => m.Nazwa == krakowInfo.Key).id;
Miasto_has_WarunkiPogodowe m_has_wp = new Miasto_has_WarunkiPogodowe()
{
idMiasto_FK = miastoId,
idWarunkiPogodowe_FK = warunki.id
};
entity.AddToMiasto_has_WarunkiPogodowe(m_has_wp);
entity.SaveChanges();
this.dataGridViewKrakow.Rows.Add(warunki);
}
}
}
class MiastoContainer
{
string miastoName;
public string MiastoName
{
get { return miastoName; }
set { miastoName = value; }
}
string panstwo;
public string Panstwo
{
get { return panstwo; }
set { panstwo = value; }
}
public MiastoContainer()
{ }
public MiastoContainer(string miasto, string panstwo)
{
this.MiastoName = miasto;
this.Panstwo = panstwo;
}
public void Add(MiastoContainer item)
{
((ICollection<MiastoContainer>)this).Add(item);
}
}
}
Your locks are completely useless. As you are locking on an object that you just created, each lock will have it's own identifier and does not affect each other at all.
You need all locks that should exclude each other to use the same object as identifier.
System.Timers.Timer lets you set the SynchronizingObject so that it will invoke the callback on the UI thread. When you create your timers, write:
this.timerKrakow.SynchronizingObject = this;
The timer's elapsed event will then be invoked on the UI thread. That eliminates the need for locks in your event handlers.
You could do the same thing, by the way, with a System.Windows.Forms.Timer, which always invokes the event handler on the UI thread.
The drawback to raising the event on the UI thread is that it might block the user interface. It depends on how much time is spent in the event handler. If your event handler is very quick, then this isn't a problem. If it will take 100 milliseconds to process the event handler, though, you probably don't want to do it on the UI thread.
If you elect not to do it on the UI thread, you need to synchronize access to the UI. The timer event handler can't just modify user interface elements. Instead, you need to call this.Invoke so that any UI modification is done on the UI thread.
I strongly suggest that you NOT use System.Timers.Timer. As the documentation states:
The Timer component catches and
suppresses all exceptions thrown by
event handlers for the Elapsed event.
This behavior is subject to change in
future releases of the .NET Framework.
In other words, if there is a bug in your event handler that throws an exception, you will never know it. I suggest using System.Windows.Forms.Timer or System.Threading.Timer instead.
I don't fully understand your question, but (unless I'm mistaken) the timer callbacks occur in the ThreadPool (or the GUI thread, dependent on usage), so starting them in different threads is pointless.
It seems to me that you are accessing DataGridView directly from another thread. You should not do that. UI controls must always be called from the UI thread. You can use the ISynchronizeInvoke interface to pass the data into correct thread.
this.dataGridViewNowyYork.Invoke(new Action(() => {
this.dataGridViewNowyYork.Rows.Add(warunki);
}), null);

Categories

Resources