使用什么选项代替while循环

时间:2018-09-09 20:36:50

标签: c#

下面的方法有效,但是我不喜欢使用while循环。在这里可以使用示例的其他选项吗?

此方法是从外部源调用的com对象的一部分。我必须用大约30种其他方法做同样的事情。立即返回所有结果,大约需要3毫秒。提到的队列由另一个线程中的任务监视。运行执行后,将结果放回skyCommand中,然后将其存储在ConcurrentDictionary中。 while循环只是在等待它的出现或超时。

   public void AxisStop(int axis)
    {
        var validAxis = ValidateAxis(axis);
        var id = Convert.ToInt32($"10{RandomNumber()}");
        var skyAxisStop = new SkyAxisStop {Id = id};
        skyAxisStop.AxisStop(validAxis);
        TelescopeHardware.SkyRequestQueue.Enqueue(skyAxisStop);
        var timer = new Stopwatch();
        timer.Start();
        while (timer.Elapsed.TotalSeconds < ReplyTimer && !TelescopeHardware.SkyResultDictionary.ContainsKey(id))
        {
            if (!TelescopeHardware.SkyResultDictionary.TryRemove(id, out var skyCommand)) continue;
            if (skyCommand.Successful) 
            {
                // deal with the results here...
            }
            else
            {
                throw skyCommand.Exception;
            }
            break;
        }
        if (timer.Elapsed.TotalSeconds >= ReplyTimer) throw new Exception("Timeout waiting on reply");
        timer.Stop();
    }

0 个答案:

没有答案
相关问题