在C#中满足条件后执行任务 [英] Executing task after condition is met in c#
问题描述
假设我们有:
bool condition = false;
现在我要开始一个新任务:
Now I want to start a new task:
new Task(() =>
{
Do something as soon as condition == true;
}).Start();
一段时间后,另一个线程/任务会将条件更改为true
The condition will be changed to true by another Thread/Task after sometime
我该怎么办?
我有一个程序可以将一个文件夹备份到另一个文件夹.我可以设置多个文件夹(例如A-> B,C-> D).比起启动程序,它开始复制文件.
I have a program for backuping one folder, to another. I can set multiple folders (for axample A -> B, C -> D). Than I start the program and it starts copying files.
但是当程序已经运行时,当我添加新文件夹(E-> F)时,我必须再次手动启动它(完成A-> B和C-> D后),以使他执行E->
But when I add new folder (E -> F) when the program is already running, I must start it manually again (after it finishes doing A -> B and C -> D) for making him do E -> F.
我想要它,当添加一个新文件夹时,在完成当前作业后自动重新开始以创建新文件夹.
I want it, when adding a new folder, start automatically again after current job is done, to do the new one.
推荐答案
如果我正确地理解您的意思,那么您正在寻找这样的东西:
If I understand you right, you are looking for something like this:
//TODO: do not forget to dispose m_Condition
ManualResetEventSlim m_Condition = new ManualResetEventSlim(false);
public bool Condition {
get {
return m_Condition.IsSet;
}
set {
if (value)
m_Condition.Set();
else
m_Condition.Reset();
}
}
...
Task myTask = Task.Run(() => {
m_Condition.Wait();
//TODO: put relevant code here
});
将Condition
切换到true
后,任务将立即开始:
The task will start as soon as Condition
is switched into true
:
Condition = true; // this unlock myTask
这篇关于在C#中满足条件后执行任务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!