Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
299 views
in Technique[技术] by (71.8m points)

c# - Is there a way Task.Run changes control flow in main thread?

I am trying to do some experiment on this scenario,

  1. 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.
  2. 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?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
等待大神答复

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...