[英]How can I execute code if something is true, continue executing the code indefinitely, but stop evaluating the if statement?
[英]How to stop executing all tasks for 3 minutes and then continue executing code
我有正在運行Work方法的任務
private void Work(Crawler crawler, PropertyBag propertyBag) {}
現在,我想停止所有任務3分鍾,然后繼續執行。 我嘗試
Thread.Sleep
但不起作用。 任務仍在工作。 什么是停止任務3分鍾然后繼續的好解決方案。 也許鎖定並且該怎么做?
沒有辦法隨意地自動暫停和恢復任務。 但是,您可以在可能想要暫停的代碼中放置特殊的“觀察者”,例如ManualResetEvent.WaitOne()
語句,並隨時從其他線程重置它們。
Thread.Sleep
無法工作,因為它使當前線程休眠。
如果您不使用TPL手工創建線程,則希望有一個線程列表/數組。 您可以使用Thread.Suspend和Thread.Resume方法。
foreach (var t in threads) t.Suspend();
// Then in 3 minutes.
foreach (var t in threads) t.Resume();
請注意,“睡眠/恢復”已過時!
編輯
如果沒有線程列表,則可以使用ManualResetEvent
。 在嘗試任何工作之前,請在Work方法中對其執行.WaitOne()
。
在主線程上調用.Reset
當您想休眠任務時,然后在3分鍾內調用.Set
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.