await Task.Run 花费的时间比预期的要长
await Task.Run taking longer than expected
对于案例 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 <<-- 调用 PulseWait 之前的行,持续时间为 400 毫秒
33653,2019:07:12:01:15:35.591,13,发送请求,:I1250100
33654,2019:07:12:01:15:35.610,13,接收响应,:I1250100,=
33655,2019:07:12:01:15:36.026,13,发送请求,:I1B70100
33656,2019:07:12:01:15:36.067,13,接收响应,:I1B70100,=
33657,2019:07:12:01:15:36.067,13,发送请求,:j1
33658,2019:07:12:01:15:36.120,13,ReceiveResponse,:j1,=DDCDBD
33659,2019:07:12:01:15:36.120,13,发送请求,:j2
33660,2019:07:12:01:15:36.165,13,接收响应,:j2,=67CF8A
33661,2019:07:12:01:15:36.467,13,发送请求,:j1
33662,2019:07:12:01:15:36.484,13,ReceiveResponse,:j1,=10CEBD
33663,2019:07:12:01:15:36.484,13,发送请求,:j2
33664,2019:07:12:01:15:36.501,13,接收响应,:j2,=67CF8A
33665,2019:07:12:01:15:36.808,13,发送请求,:j1
33666,2019:07:12:01:15:36.842,13,ReceiveResponse,:j1,=3CCEBD
33667,2019:07:12:01:15:36.842,13,发送请求,:j2
33668,2019:07:12:01:15:36.868,13,接收响应,:j2,=67CF8A
33669,2019:07:12:01:15:37.170,13,发送请求,:j1
33670,2019:07:12:01:15:37.188,13,ReceiveResponse,:j1,=6BCEBD
33671,2019:07:12:01:15:37.188,13,发送请求,:j2
33672,2019:07:12:01:15:37.204,13,接收响应,:j2,=67CF8A
33673,2019:07:12:01:15:37.221,5,b__0,PulseGuide=False <<--PulseWait 在启动后 1.631 毫秒完成
async
和 await
的目的是让事情变得简单。但就像所有让事情变得简单的事情一样,它也伴随着完全控制正在发生的事情的成本。在这里,它实际上是一般异步编程的成本。异步编程的要点是释放当前线程,以便当前线程可以离开并做其他事情。但是如果在当前线程上做了其他事情,那么你正在做的事情的继续必须等到那件事完成。 (即 在 之后 await
可能不会在任务完成后立即发生)
因此,虽然异步编程有助于 整体 性能(例如提高 Web 应用程序的整体吞吐量性能),但实际上会损害任何 应用程序的性能 具体任务。如果每一毫秒对你来说都很重要,你也许可以自己完成低级任务,比如创建一个线程(如果这真的需要 运行 在一个单独的线程上)。
这里有一个简单的例子来证明这一点:
var s = new Stopwatch();
// Test the time it takes to run an empty method on a
// different thread with Task.Run and await it.
s.Start();
await Task.Run(() => { });
s.Stop();
Console.WriteLine($"Time of Task.Run: {s.ElapsedMilliseconds}ms");
// Test the time it takes to create a new thread directly
// and wait for it.
s.Restart();
var t = new Thread(() => { });
t.Start();
t.Join();
s.Stop();
Console.WriteLine($"Time of new Thread: {s.ElapsedMilliseconds}ms");
输出会有所不同,但看起来像这样:
Time of Task.Run: 8ms
Time of new Thread: 0ms
在一个有很多其他事情正在进行的应用程序中,如果其他一些操作在 await
期间使用线程,那么 8 毫秒可能会更多。
这并不是说您应该 使用Thread
。 t.Join()
不是异步操作。它会阻塞线程。所以如果 PulseWait
运行s 在 UI 线程上(如果这是一个 UI 应用程序),它会锁定 UI 线程,这是一个坏用户经验。在那种情况下,您可能无法避免使用异步代码的成本。
如果这 不是 具有 UI 的应用程序,那么我完全不明白您为什么需要在不同的线程上执行所有这些操作。也许你可以......不要那样做。
对于案例 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 <<-- 调用 PulseWait 之前的行,持续时间为 400 毫秒 33653,2019:07:12:01:15:35.591,13,发送请求,:I1250100 33654,2019:07:12:01:15:35.610,13,接收响应,:I1250100,= 33655,2019:07:12:01:15:36.026,13,发送请求,:I1B70100 33656,2019:07:12:01:15:36.067,13,接收响应,:I1B70100,= 33657,2019:07:12:01:15:36.067,13,发送请求,:j1 33658,2019:07:12:01:15:36.120,13,ReceiveResponse,:j1,=DDCDBD 33659,2019:07:12:01:15:36.120,13,发送请求,:j2 33660,2019:07:12:01:15:36.165,13,接收响应,:j2,=67CF8A 33661,2019:07:12:01:15:36.467,13,发送请求,:j1 33662,2019:07:12:01:15:36.484,13,ReceiveResponse,:j1,=10CEBD 33663,2019:07:12:01:15:36.484,13,发送请求,:j2 33664,2019:07:12:01:15:36.501,13,接收响应,:j2,=67CF8A 33665,2019:07:12:01:15:36.808,13,发送请求,:j1 33666,2019:07:12:01:15:36.842,13,ReceiveResponse,:j1,=3CCEBD 33667,2019:07:12:01:15:36.842,13,发送请求,:j2 33668,2019:07:12:01:15:36.868,13,接收响应,:j2,=67CF8A 33669,2019:07:12:01:15:37.170,13,发送请求,:j1 33670,2019:07:12:01:15:37.188,13,ReceiveResponse,:j1,=6BCEBD 33671,2019:07:12:01:15:37.188,13,发送请求,:j2 33672,2019:07:12:01:15:37.204,13,接收响应,:j2,=67CF8A 33673,2019:07:12:01:15:37.221,5,b__0,PulseGuide=False <<--PulseWait 在启动后 1.631 毫秒完成
async
和 await
的目的是让事情变得简单。但就像所有让事情变得简单的事情一样,它也伴随着完全控制正在发生的事情的成本。在这里,它实际上是一般异步编程的成本。异步编程的要点是释放当前线程,以便当前线程可以离开并做其他事情。但是如果在当前线程上做了其他事情,那么你正在做的事情的继续必须等到那件事完成。 (即 在 之后 await
可能不会在任务完成后立即发生)
因此,虽然异步编程有助于 整体 性能(例如提高 Web 应用程序的整体吞吐量性能),但实际上会损害任何 应用程序的性能 具体任务。如果每一毫秒对你来说都很重要,你也许可以自己完成低级任务,比如创建一个线程(如果这真的需要 运行 在一个单独的线程上)。
这里有一个简单的例子来证明这一点:
var s = new Stopwatch();
// Test the time it takes to run an empty method on a
// different thread with Task.Run and await it.
s.Start();
await Task.Run(() => { });
s.Stop();
Console.WriteLine($"Time of Task.Run: {s.ElapsedMilliseconds}ms");
// Test the time it takes to create a new thread directly
// and wait for it.
s.Restart();
var t = new Thread(() => { });
t.Start();
t.Join();
s.Stop();
Console.WriteLine($"Time of new Thread: {s.ElapsedMilliseconds}ms");
输出会有所不同,但看起来像这样:
Time of Task.Run: 8ms
Time of new Thread: 0ms
在一个有很多其他事情正在进行的应用程序中,如果其他一些操作在 await
期间使用线程,那么 8 毫秒可能会更多。
这并不是说您应该 使用Thread
。 t.Join()
不是异步操作。它会阻塞线程。所以如果 PulseWait
运行s 在 UI 线程上(如果这是一个 UI 应用程序),它会锁定 UI 线程,这是一个坏用户经验。在那种情况下,您可能无法避免使用异步代码的成本。
如果这 不是 具有 UI 的应用程序,那么我完全不明白您为什么需要在不同的线程上执行所有这些操作。也许你可以......不要那样做。