简体   繁体   English

C#中怪异的多线程行为

[英]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: 此外,每次启动新线程时,它都会写入“ 1”进行记录:

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: 和客户端处理线程,该线程将“ 2”写入日志文件并处理传入的连接:

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. 我还有一个小应用程序,它每隔50毫秒连接到服务器并发送/接收一些数据。 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". 如果我仅启动一个客户端,则“ 1”和“ 2”的数量相等,但是如果我在不同计算机上启动多个客户端实例,则“ 2”的数量比“ 1”高5%。 It means that my client thread's procedure was called 5% more times than a actually requested. 这意味着我的客户端线程的过程被调用的次数比实际请求多5%。 How it could be possible? 怎么可能呢? for example I have 3 clients. 例如我有3个客户。 Each client performs 1000 sessions with the server. 每个客户端与服务器执行1000个会话。 In result, I have: 结果,我有:

  • 3000 successful sessions on client side 客户端成功会话3000次
  • 3119 amount of connections accepted by listen socket (and writes "1") 3119侦听套接字接受的连接数(并写入“ 1”)
  • 3273 times client thread function were called 3273次客户端线程函数被调用

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. 重新启动Visual Studio并重建项目后,该问题已自行解决。 I don't know what to say. 我不知道该说些什么。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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