System.Timers.Timer

S

shayke

Hi all

Is it true that System.Timers.Timer runs on a seperate thread, using the
thread pool.
if so, it means that the elapsed callback will never be on the context that
the timer was created in.
What do i have to do to achieve that : receive the elapsed event handler in
the thread that created the timer.

Regards
Shayke
 
V

Vadym Stetsyak

Yes, Elapsed callback will be executed on the separate thread.

Why do you need such behavior?

Have you checked
System.Windows.Forms.Timer?
 
S

shay azulay

Hi Vadym

Thanks for your reply.
My need for the timer to callback in it's creator thread comes from a
bigger need.
i have been trying (with no luck) to execute code on specific thread
context.something like SynchronizationContext does BUT for any thread
and not just the UI thread.
Have you any idea how i can achieve that?

Regards
Shay
 
J

Jon Skeet [C# MVP]

shay azulay said:
Thanks for your reply.
My need for the timer to callback in it's creator thread comes from a
bigger need.
i have been trying (with no luck) to execute code on specific thread
context.something like SynchronizationContext does BUT for any thread
and not just the UI thread.
Have you any idea how i can achieve that?

Well, what else is this thread doing? You can't make one thread just
hijack another - the thread you want to run code on needs to be
"looking" for the work to do. Something like the UI message pump, or a
producer consumer queue. For an example of the latter, see
http://www.pobox.com/~skeet/csharp/threads/deadlocks.shtml (half way
down).
 
G

Guest

Hi Shayke,

shayke said:
Hi all

Is it true that System.Timers.Timer runs on a seperate thread, using the
thread pool.
if so, it means that the elapsed callback will never be on the context that
the timer was created in.
What do i have to do to achieve that : receive the elapsed event handler in
the thread that created the timer.

Regards
Shayke

Depends on the SynchronizingObject property of the Timer instance.

From MSDN.
<quote>
When SynchronizingObject is a null reference (Nothing in Visual Basic), the
method that handles the Elapsed event is called on a thread from the
system-thread pool. For more information on system-thread pools, see
ThreadPool.

When the Elapsed event is handled by a visual Windows Forms component, such
as a button, accessing the component through the system-thread pool might
result in an exception or just might not work. Avoid this effect by setting
SynchronizingObject to a Windows Forms component, which causes the method
that handles the Elapsed event to be called on the same thread that the
component was created on.
</quote>

Kind regards,
 

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