Click here to Skip to main content
15,888,733 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
The goal is to elapse Timers.Timer on a specific thread i choose.
I need to set ISynchronizeInvoke instance to Timer.SynchronizingObject Property.
I need to create ISynchronizeInvoke instance on a the specific thread, but i can't:

C#
    public Form1()
    {
        InitializeComponent();

        this.Load += delegate
        {
            new Thread(Thread).Start();
        };
    }

    System.Timers.Timer timer = new System.Timers.Timer();

    void Thread()
    {
        ISynchronizeInvoke invoke = ?
        timer = new System.Timers.Timer();
        timer.SynchronizingObject = invoke;
    }
}


Notes:
The next ways are not solutions:
1. lock
2. AutoReset
3. Not ready Control like Button to elapse on UI thread.

I need to run Timers.Timer on another not UI single thread like i run Windows Forms on UI thread.
Posted
Updated 9-May-15 2:21am
v3

1 solution

You don't get to tell it which thread to use. The Timer doesn't even know which thread it's doing use! From the documentation:

System.Threading.Timer, which executes a single callback method on a thread pool thread at regular intervals.

You cannot force a thread to execute code whenever you want. The target thread determines when it will accept an Invoke. The only way I know if doing something like this is to implement a kind of message pump with a SynchronizationContext in your target thread.

The most complete explanation I know of for this is here[^], complete with examples of implementation.
 
Share this answer
 
Comments
Ziya1995 9-May-15 9:48am    
You are wrong, SynchronizingObject set to Control makes sure it will run on UI thread.
It fires Elapsed event on UI thread, i wanna fire it on a thread i created.

So, i can tell Timers.Timer to run on UI thread.
Now, how to tell it to run on my thread?

You mean i can't fire Elapsed event on my thread like i fire on UI thread by Invoke?
Dave Kreskowiak 9-May-15 10:20am    
No, I am NOT wrong.

YES! It's a POOL THREAD the timer fires on. There is no way to tell it which thread to use.
Ziya1995 9-May-15 10:24am    
> YES! It's a POOL THREAD the timer fires on.
If i tell - it fires on UI thread.
If i don't tell - it fires on a pool thread.
Result - i can tell.

> There is no way to tell it which thread to use.
I can tell to run on UI thread by invoking, but if i wanna invoke it on none UI thread, i need to use SynchronizationContext class.
Dave Kreskowiak 9-May-15 11:48am    
Alright. You're being an ass. You said you wanted to tell it WHICH thread to use. The ONLY thread you can tell it to use is the UI thread. You cannot tell it to use ANY ARBITRARY thread.

Have a nice life.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900