Waiting for a result without blocking a thread

半城伤御伤魂 提交于 2021-01-28 03:04:15

问题


I have this code doing what I want:

        TriggerSomeExternalProcess();
        double secondsElapsed = 0;
        DateTime startTime = DateTime.UtcNow;
        double timeoutInSeconds = 10;
        while (secondsElapsed < timeoutInSeconds) {
            // TODO: this seems bad...
            secondsElapsed = DateTime.UtcNow.Subtract(startTime).TotalSeconds;
        }
        CheckStatusOfExternalProcess();

The goal is to TriggerSomeExternalProcess and then CheckStatusOfSomeExternalProcess - but that process runs on the same thread so I can't do Thread.Sleep(). It's an ongoing process that can't be awaited.

I feel like the above while loop is wrong - what pattern do you employ when you need to wait without blocking your thread?

copy-pasted from a comment on one of the answers unfortunately I can't touch the code in the ExternalProcess. I'm writing a test and those are the methods I have access to. I know it's less than ideal


回答1:


Instead of using a CheckStatusOfExternalProcess() Method u may be able to add an StatusChangedEvent onto the ExternalProcess thing and attach a EventHandler onto it. That way your eventhandler gets called, when the status has changed.

Is that a possibility for you?

Btw: If both of your processes run on the same Thread - how can that be not blocking?




回答2:


I assume the process that's external is not your own. Therefore it can't take a callback action. It can't give a heartbeat (send periodically back it's current status). And it can't subscribe to it's status changing. These would be the normal ways to deal with it.

In which case you could just use something like this

Task.delay(TimeSpan.FromSeconds(10))).ContinueWith(() => CheckStatusOfExternalProcess())

continue with will fire as soon the first task is complete but now you can continue on in your code without worrying about it



来源:https://stackoverflow.com/questions/42281036/waiting-for-a-result-without-blocking-a-thread

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!