2

私は SerialPort で通信するプログラムに取り組んでおり、それに問題があります。その通信は50%以下です。そうでない場合は、ほとんどの場合タイムアウトになります。

この問題を調査したところ、デフォルトでグローバルまたはシステム タイマーの分解能が最小で 10 ミリ秒以上であることがわかりました。

シリアル通信 (RTS) と Windows 7

したがって、通信で Thread.Sleep を使用して X ミリ秒の間一時停止する場合、ノーオペレーションまたは一時停止の場合は 10 ミリ秒以上が最適です。

私の場合、プログラムが外部デバイスと通信するには長すぎます。デバイスは、プログラムから要求を受け取るとすぐに 10 ミリ秒以内に応答します。プログラムが応答を受け取る準備ができていない場合、プログラムはタイムアウトになります。

この問題を解決する唯一の方法は、システム タイマーの解像度を調整または変更することです。そのために、winmm.dll の Windows メソッド timeBeginPeriod と timeEndPeriod を使用するように言われました。プログラムの Windows .NET バージョンにこれらのメソッドをインポートすることはできますが、.NET フレームワークでこれらのメソッドに代わるものがあるかどうかを知りたいです。

4

1 に答える 1

2

If your goal is to avoid invoking platform specific DLL functions and just using the .Net framework then for short timeouts a loop with the System.Diagnostics.Stopwatch might be your best bet.

The Stopwatch will automatically use the high resolution timer when present.

public static void Pause(long ms) 
{
    Stopwatch t = new Stopwatch();
    t.Start();
    while(t.ElapsedMilliseconds < ms) { }
    t.Stop();
}

This will block your calling thread and hog the CPU while in the pause loop, to mitigate some of this (if you are using a multi-core system you can set your process's or thread's affinity to another core. How Can I Set Processor Affinity in .NET?

于 2012-11-05T15:17:27.670 に答える