1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

メモ C# lock を使用した珍しい不具合

Posted at

TCP/IP使用したサーバー側のソケット通信にて複数のクライアントからデータに対してアクセスが行われる為、下記のような、lockを行い排他制御を行った。
下記コードが最適では、無かったが、その際に遭遇したlockの動作についてメモする

ReceiveCallBackを再起動後にLogを出力するコードを記載していた

Sample.cs

        private static object lockReceiveCallBack = new object();
        
        void ReceiveCallBack(IAsyncResult ar)
        {
            lock (lockReceiveCallBack)
            {
                // 受信処理
                LogOut("ReceiveCallBack Start");

                // 再起動
                clientSocket.BeginReceive(dataBuffer, 0, 1024, SocketFlags.None, ReceiveCallBack, clientSocket);
                        });
                LogOut("ReceiveCallBack End");
            }
            
        }

同じクライアントから通信が連続してあった場合、実行したLogの結果が、以下になる

result.txt
ReceiveCallBack Start
ReceiveCallBack Start
ReceiveCallBack Start
ReceiveCallBack End
ReceiveCallBack End
ReceiveCallBack End

想定では以下になる

result.txt
ReceiveCallBack Start
ReceiveCallBack End
ReceiveCallBack Start
ReceiveCallBack End
ReceiveCallBack Start
ReceiveCallBack End

「ReceiveCallBack End」が実行される前に次の受信イベントが発生し、ReceiveCallBackに再入して処理が行われて、「ReceiveCallBack End」のLog出力が後回しになっている。
lockを実行している為、再入はできないと考えていたが、想定とは違う結果になった。同じスレッドという認識で動作しているのか、それとも別の原因か
原因究明は、できなかったが、lockの使用をやめたら解決した
何れにしろ、lockを実行する範囲は限定的にする必要がある

1
0
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?