简体   繁体   中英

Weird multithreading behavior in C#

I have a listener thread function, which waits for incoming connection and starts a new thread for every client. Also it writes "1" to log every time when it starts a new thread:

void ListenWorkerDoWork(object sender, DoWorkEventArgs e) {
    try {
        var tcpListener = new TcpListener(IPAddress.Any, 843);
        tcpListener.Start();
        var worker = sender as BackgroundWorker;

        if (worker != null) {
            while (!worker.CancellationPending) {
                var client = tcpListener.AcceptTcpClient();
                var clientThread = new Thread(HandleClientComm) { IsBackground = true };
                clientThread.Start(client);
                Logger.Instance.WriteToLog(Logger.Type.Info, "1");
            }
        }
    } catch (Exception ex) {
        Logger.Instance.WriteToLog(Logger.Type.Error, string.Format("An error has occured while listening on port 843:{0}{1}", Environment.NewLine, ex));
    }
}

and Client handling thread which writes "2" to the log file and processes incoming connection:

private void HandleClientComm(object client) {
    Logger.Instance.WriteToLog(Logger.Type.Info, "2");
    [...]
}

Also I have small application which connects to the server every 50 msec and send/receive some data. If I'm start only one client, then amount of "1" and "2" is equal, but if I start several instances of client on different computers, then amount of "2" is 5% higher than "1". It means that my client thread's procedure was called 5% more times than a actually requested. How it could be possible? for example I have 3 clients. Each client performs 1000 sessions with the server. In result, I have:

  • 3000 successful sessions on client side
  • 3119 amount of connections accepted by listen socket (and writes "1")
  • 3273 times client thread function were called

Thank You!

Updated:

Log writing function is thread safe:

    public void WriteToLog(Type type, object message) {
        lock(writelock) {
            String str = typeText[(int)type] + DateTime.Now.ToString() + " : " + message.ToString();
            Console.WriteLine(str);
            if (stream != null) {
                stream.WriteLine(str);
                stream.Flush();
            }
        }
    }

The problem was solved by itself after restarting Visual Studio and rebuilding the project. I don't know what to say.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM