如何在c#中重启正在运行的线程? [英] How to restart a running thread in c#?

查看:777
本文介绍了如何在c#中重启正在运行的线程?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Hi guys

Public Class1
{
         public int Func()
         {

            Blah Blah Blah

         }

         public int Func2()
         {

           Blah Blah Blah

         }


         void main()
         {
           int value1;
           Class1 CL1 =new Class1();
           var thread1 = new Thread(() =>{value1 = CL1.Func();}); 
 var thread2 = new Thread(() =>{ System.ServiceProcess.ServiceBase.Run(Func2());});
         }
}

Here goes my question,
I want to schedule the thread1 i.e I want to call method(Func) at regular intervals and I will compare the values returned by it each time.Based on the comparison outcome I want to restart the thread2 even though it is running.Is it possible to achieve this.
Thanks in advance.

推荐答案

没有重启线程这样的概念。你可以让一些线程终止(比如,中止它,或者等到它退出)并用相同的方法创建一个线程,但它将是另一个线程。问题是:为什么?



更好的方法是在循环中重用相同的线程,使用事件方式句柄通过其他线程限制它。我在过去的答案中描述了这种技术:

http:// www .codeproject.com / Answers / 317777 / pause-running-thread#answer2 [ ^ ],

使代码线程安全 [ ^ ],

Thread中的ManualResetEvent和AutoResetEvent [ ^ ],

在webservice中运行一个永远不会终止的作业/线程/进程(asp.net) [ ^ ]。



-SA
There is no such concept as "restart a thread". You can have some thread terminated (say, abort it, or wait until it exits) and create a thread with the same method, but it will be another thread. The question is: why?

The better approach is to reuse the same thread in cycle, throttling it by some other thread using an event way handle. This technique is described in my past answers:
http://www.codeproject.com/Answers/317777/pause-running-thread#answer2[^],
Making Code Thread Safe[^],
ManualResetEvent and AutoResetEvent in Thread[^],
Running exactly one job/thread/process in webservice that will never get terminated (asp.net)[^].

—SA


这篇关于如何在c#中重启正在运行的线程?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆