while循环在等待消息时做某事

时间:2016-05-30 18:00:50

标签: c# multithreading

我有一个等待UDP消息的程序,

有没有办法在等待UDP消息时做某事?

所以程序会做一些事情,但是只要收到一条消息它会去做另外的事情吗?

感谢

2 个答案:

答案 0 :(得分:0)

while (true)
        {
            counter += 1;
            Console.WriteLine("Waiting for connection...");
            clientSocket = serverSocket.AcceptTcpClient();
            Console.WriteLine(" >> " + "Client No:" + Convert.ToString(counter) + " started!");
            handleClinet client = new handleClinet();
            client.startClient(clientSocket, Convert.ToString(counter));
        }

参考:http://csharp.net-informations.com/communications/csharp-multi-threaded-server-socket.htm

更新:如果您希望主线程空闲并创建另一个线程来等待连接,请阅读本文:http://www.codeproject.com/Articles/463947/Working-with-Sockets-in-Csharp

String theMessageToReceive = Encoding.Unicode.GetString(bytes, 0, bytesRec);
    while (senderSock.Available > 0)
    {
      bytesRec = senderSock.Receive(bytes);
      theMessageToReceive += Encoding.Unicode.GetString(bytes, 0, bytesRec);
    // Do something
    }

答案 1 :(得分:0)

首先,多个while循环不是多线程的。 C#是一种通过代码从上到下工作的语言。 第二:

//create new worker
public System.ComponentModel.BackgroundWorker worker;
// Start new thread
private void StartBackgroundWorker (...) {...}
//what should the worker do
private void worker_DoWork (...) {...}
//if the progress has changed while working
private void worker_ProgressChanged (...) {...}
//thread is finished
private void worker_RunWorkerCompleted (...) {...}

这些是该任务所需的所有方法(也许可能更多)。 但我认为在学习C#时你应该开始降低一点。