I am trying to do some experiment on this scenario,
- Say the main thread creates a Process and the process's job is to copy something, which takes observable duration(that's why it's desired to be cancellable) to complete, named
copyProcess
here.
- I want to add another task in parallel with this copying, aiming to query some status and abort the process when the status returns false. The pseudo code is like this:
void Main(){
Url jobUrl = "someUrl";
Process copyProcess = new Process();
Task<bool> queryTask = Task.Run(()=>queryStatus(jobUrl)).ContinueWith(t=>{
if(!t.Result || t.Faulted)
copyProcess.Kill();
})
copyProcess.WaitForExit();
}
bool queryStatus(Url jobUrl){
bool status = httpGetStatus(jobUrl);
while(status == incomplete){
status = httpGetStatus(jobUrl);
}
return status;
}
The problem is, if the queryTask is running too fast and enters into the callback in ContinueWith
, it would try to abort a process that has not started. Even if it's fine, copyProcess
will invoke WaitForExit
next, which is not the desired behavior.
Is there a way to change the control flow so the part starting from copyProcess.WaitForExit();
can be skipped? My imagination is to set a variable in the ContinueWith
and use that as a condition for copyProcess.WaitForExit();
But there is race condition here, and locking may not work as that way there is no point to make this paralization.
Or is there a better implementation under this scenario?
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…