C#自旋的艺术
CODE1:
while (status == ServerStatus.Started) { if (*TaskLocker > 0) { for (int i = 0; i != *Level; i++) { ComputeListenerMemory memory = memories[i]; if (*memory.Flag == 0x01) { Interlocked.Decrement(ref *TaskLocker); *memory.Flag = 0x03; Parallel.Invoke(memory.BeginComputeHandler); } } } }
CODE2:
while (status == ServerStatus.Started) { if (*TaskLocker > 0) { for (int i = 0; i != *Level; i++) { ComputeListenerMemory memory = memories[i]; if (*memory.Flag == 0x01) { Interlocked.Decrement(ref *TaskLocker); *memory.Flag = 0x03; Parallel.Invoke(memory.BeginComputeHandler); } } } spin.SpinOnce(); }
CODE3:
while (status == ServerStatus.Started) { if (*TaskLocker > 0) { for (int i = 0; i != *Level; i++) { ComputeListenerMemory memory = memories[i]; if (*memory.Flag == 0x01) { Interlocked.Decrement(ref *TaskLocker); *memory.Flag = 0x03; Parallel.Invoke(memory.BeginComputeHandler); } } } else { spin.SpinOnce(); } }
CODE1响应速度最快 约4ms 但是至少占用了CPU资源10%
CODE2响应速度最慢 因为spin固定占用4ms 故约10ms 但是CPU资源占用降低到1%
CODE3是一个最佳平衡点,且CPU占用率低