2017-08-29 33 views
1

我想创建一个线程,每工作1秒就会工作,当它完成时(当我变成真),它将发送另一个对象的事件。
c#线程每1秒工作一次,甚至发送

fun(run on another thread) 
{ 
    while (true) 
    { 
    if(cond==true) 
    { 
     send event 
     break 
     finish the thread 
    } 
    else 
     sleep(1000)(and to the function again 
    } 
} 

的另一个对象会做一些事情,当它得到事件,该函数返回true,线程完成

我认为线程池是最好的在这里。
但我没有成功写在c#上的简单代码来实现它

+0

我想你需要提供一些你想要做的更多细节。这是一个很好的资源,虽然这可能会回答你的问题http://www.albahari.com/threading/ –

+1

为什么你需要每秒启动一个线程?这将创建多个线程,然后可能会在不同的时间返回,有时是真的,有时是错误的。到目前为止你所描述的你可能会更好地使用一个计时器,它可以在自己的线程中运行,并且每完成一次自动再次调用它自己。否则,我会尝试找到一种方法来将事件处理程序附加到您的条件。 – user685590

+1

如果在线程中有'while true',则10次中有9次应该使用计时器。 –

回答

0

在这种情况下,你还没有说任何否定使用计时器的东西 - 所以我会用一个。

//Declare a timer (possibly global in this instance) 
Timer _timer; 

//Put this where you want to start checking. (possibly in main thread) 
Timer _timer = new System.Timers.Timer(1000); 
//Check every second and fire the timer_Elapsed event 
_timer.Elapsed += new ElapsedEventHandler(timer_Elapsed); 
//Start the timer 
_timer.Enabled = true; 
//Stop overlapping timers (we will start the timer after it completes it's check) 
_timer.AutoReset = false; 

//Seperate timer event method. 
void timer_Elapsed(object sender, ElapsedEventArgs e) 
{ 
    //Check your condition here and send off event if true. this will call 
    //this method again and again every second. 
    _timer.Enabled = true; 
} 
相关问题