Are events threaded by default?

J

JSheble

Say I have two seperate timers in my app (it's strictly an example, I
don't really...) and each of the timer events calls the same method of the
form's class. Will these interfere with each other at all? Will they run
as if they're threaded?

Example:

private void timer1_Tick(object sender, System.EventArgs e)
{
this.SomeMethod()
}

private void timer2_Tick(object sender, System.EventArgs e)
{
this.SomeMethod()
}

private string SomeMethod()
{
OleDbCommand oDB = new OleDbCommand();
oDB.COnnection = new OleDbConnection(this.DSNString);

// do a bunch of other stuff

oDB.Connection.Close();
oDB.Dispose();
}
 
J

Jon Skeet [C# MVP]

JSheble said:
Say I have two seperate timers in my app (it's strictly an example, I
don't really...) and each of the timer events calls the same method of the
form's class. Will these interfere with each other at all? Will they run
as if they're threaded?

Are you interested in timers, or events in general? Events have no
special threading behaviour - whereas timers do, and the exact
semantics depend on which type of timer you're talking about.
 
B

Brian Gideon

I'm assuming you're using the System.Windows.Forms.Timer (based on the
name of the handler). If that's the case then no, events will be
executed on the main UI thread and thus will not interfere with each
other since the message pump will process them serially.

If you're using the System.Timers.Timer then events might be executed
on different threads depending on the how the SynchronizingObject
property is set. The SynchronizingObject property accepts an
ISynchronizeInvoke object. Forms and controls implement this interface
so if they are used then the timer events will be executed on a UI
thread. If the SynchronizingObject property is null then the timer
events are executed from threads in the system thread pool.

The other timer, which I know you're not speaking of, is
System.Threading.Timer. That timer always invokes the specified
callback from a thread in the thread pool.

Brian
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top