等待任务。运行时间比预期的长

问题描述 投票:0回答:1

下面的方法假设在情况0传递的持续时间(以毫秒为单位)下运行,但是我看到的是该方法可能需要2秒钟才能运行400毫秒。 Task.run是否可能需要很长时间才能启动?如果是这样,有没有更好的方法?

private static async void PulseWait(int duration, int axis){
await Task.Run(() =>
{
    try
    {
        var logaction = true;
        switch (axis)
        {
            case 0:
                var sw1 = Stopwatch.StartNew();
                if (duration > 0) duration += 20; // allowance for the call to the mount
                while (sw1.Elapsed.TotalMilliseconds <= duration) { } // wait out the duration
                _isPulseGuidingRa = false;
                logaction = false;
                break;
            case 1:
                var axis2Stopped = false;
                var loopcount = 0;

                switch (SkySettings.Mount)
                {
                    case MountType.Simulator:
                        while (!axis2Stopped && loopcount < 30)
                        {
                            loopcount++;
                            var statusy = new CmdAxisStatus(MountQueue.NewId, Axis.Axis2);
                            var axis2Status = (AxisStatus)MountQueue.GetCommandResult(statusy).Result;
                            axis2Stopped = axis2Status.Stopped;
                            if (!axis2Stopped) Thread.Sleep(10);
                        }
                        break;
                    case MountType.SkyWatcher:
                        while (!axis2Stopped && loopcount < 30)
                        {
                            loopcount++;
                            var statusy = new SkyIsAxisFullStop(SkyQueue.NewId, AxisId.Axis2);
                            axis2Stopped = Convert.ToBoolean(SkyQueue.GetCommandResult(statusy).Result);
                            if (!axis2Stopped) Thread.Sleep(10);
                        }
                        break;
                    default:
                        throw new ArgumentOutOfRangeException();
                }
                _isPulseGuidingDec = false;
                logaction = false;
                break;
        }

        var monitorItem = new MonitorEntry
        { Datetime = HiResDateTime.UtcNow, Device = MonitorDevice.Telescope, Category = MonitorCategory.Mount, Type = MonitorType.Data, Method = MethodBase.GetCurrentMethod().Name, Thread = Thread.CurrentThread.ManagedThreadId, Message = $"PulseGuide={logaction}" };
        MonitorLog.LogToMonitor(monitorItem);
    }
    catch (Exception)
    {
        _isPulseGuidingDec = false;
        _isPulseGuidingRa = false;
    }
});}

日志显示了耗时...33652,2019:07:12:01:15:35.590,13,AxisPulse,Axis1,0.00208903710815278,400,0,True <

下面的方法假设在情况0传递的持续时间(以毫秒为单位)下运行,但是我看到的是该方法可能需要2秒钟才能运行400毫秒。是...

c# wpf async-await task-parallel-library
1个回答
0
投票

asyncawait的目的是使事情变得容易。但是,就像使事情变得容易的一切一样,它也具有对发生的事情进行完全控制的代价。通常,这实际上是异步编程的成本。异步编程的重点是释放当前线程,以便当前线程可以执行其他操作。但是,如果在当前线程上完成了其他操作,则必须继续执行操作,直到完成操作为止。 (即,在任务完成后,after

© www.soinside.com 2019 - 2024. All rights reserved.