Background threading in c#
I am currently working with threading and backgroundworker in c#. The problem im having is that this. Say i have a main thread for user interaction and a worker thread to process txt files(various editing operations). Then after the backgroundthread runs its contents once, i have a timer start that performs another set of operations. I want these new operations that the timer runs ever x minutes to be run in the same background thread without running the previous txt related opera开发者_运维问答tions it ran before the timer started. How can this be done?
You should just use a System.Timers.Timer
, which will run its callback on a thread pool thread.
It shouldn't matter which specific thread you run on (as long as it's not the UI thread).
If, for some reason, it does matter (eg, if you're using a single-threaded COM object), you'll need to make a dedicated thread that waits for things to do using a thread-safe queue of delegates.
You want to use an Event Driven method to execute function calls on your worker thread from your UI thread. The way to accomplish this is using BeginInvoke, you can read more about how to use it here: http://www.dreamincode.net/forums/topic/35616-cross-thread-communication-in-c%23/
Add a while loop to the end of your background worker:
while(!stop) { Thread.Sleep(yourIntervalinMilliseconds); ... }
I'd create a stop bool somewhere that the thread looks at when you want it to kick out.
精彩评论