Click here to Skip to main content
15,887,821 members
Please Sign up or sign in to vote.
2.50/5 (2 votes)
Same for backgroundworker.runworkerasync.

I had this problem and solved it by making the timer start in the BackgroundWorker.RunWorkerCompleted. because it's on the same thread as the main one.

What I have tried:

I succeeded as said above, but don't understand why the problem?
Posted
Updated 3-Oct-16 22:31pm
Comments
Philippe Mori 4-Oct-16 9:44am    
No code, no formatting and not much effort put in asking a question...
john1990_1 4-Oct-16 14:52pm    
I made timer1.start() in lines of a thread running in background, the code executed in background but the timer which is on the UI in form didn't start.

thread1.IsBackground=true;
thread1.start();

Simple: it's a Control, which means it's a UI component (even if it isn't visible) and they can only ever be accessed on the UI thread. You could - in theory - Invoke it to start it (since Invoke moves the code to the UI thread) but that would probably defeat the purpose of the BackgroundWorker!
 
Share this answer
 
v2
As OriginalGriff wrote, the System.Windows.Forms.Timer is a UI component. Usually you get it int your application by dragging one onto a Form.
But you can instatiate it in code like you would do with every ordinary class. From any thread you like. You can then call it from that thread.

But I'd rather advise to leave those timers in UI thread because there are alternavies designed to be used in other thrads: System.Timers.Timer and System.Threading.Timer.

Of cause, if you initially used Forms.Timer because the timer call will do something in the UI, you will no longer be allowed to do that from the other timers' callback functions. Instead, you will have to add a layer of invoking.

In essence, you will have to decide where to use invoke: Calls into the timer (if it is on UI thread) or out of the timer into UI thread.
 
Share this answer
 
Comments
johannesnestler 4-Oct-16 9:46am    
5ed - But, I would always suggest marshal to UI thread from timer not the other way round. That OP wanted a timer in a Background thread is a STRONG HINT he wanted to use something like System.Timers.Timer but didn't know about it...
lukeer 4-Oct-16 10:08am    
Full Ack. And thanks.

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