简体   繁体   English

C#中的后台线程

[英]Background threading in c#

I am currently working with threading and backgroundworker in c#. 我目前正在使用C#中的线程和backgroundworker。 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). 说我有一个用于用户交互的主线程和一个用于处理txt文件(各种编辑操作)的辅助线程。 Then after the backgroundthread runs its contents once, i have a timer start that performs another set of operations. 然后,在backgroundthread运行一次其内容之后,我将启动一个计时器,执行另一组操作。 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 operations it ran before the timer started. 我希望计时器运行x分钟的这些新操作在同一后台线程中运行,而不运行计时器启动之前运行的与txt相关的先前操作。 How can this be done? 如何才能做到这一点?

You should just use a System.Timers.Timer , which will run its callback on a thread pool thread. 您应该只使用System.Timers.Timer ,它将在线程池线程上运行其回调。

It shouldn't matter which specific thread you run on (as long as it's not the UI thread). 您在哪个特定线程上运行都无关紧要(只要它不是UI线程即可)。
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. 如果由于某种原因确实很重要(例如,如果您使用的是单线程COM对象),则需要创建一个专用线程,以使用线程安全的委托队列等待事情发生。

You want to use an Event Driven method to execute function calls on your worker thread from your UI thread. 您想使用事件驱动方法从UI线程对工作线程执行函数调用。 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/ 完成此操作的方法是使用BeginInvoke,您可以在此处详细了解如何使用它: 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循环添加到后台工作者的末尾:

while(!stop) { Thread.Sleep(yourIntervalinMilliseconds); while(!stop){Thread.Sleep(yourIntervalinMilliseconds); ... } ...}

I'd create a stop bool somewhere that the thread looks at when you want it to kick out. 我会在您希望将其踢出时在该线程所处的位置创建一个止停螺栓。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM