我如何等待函数的 return 值

How i wait the return value of a function

我有一个函数可以用来向服务器发送消息。服务器 return 是一个类似于 'true' 或 'false' 的字符串,客户端 return 是服务器编辑的值 return。我的问题是,当我根据请求调用 ClientReturn 时,我在函数中得到 return 但没有进入另一个函数字符串,或者 if(ClientReturn() == "false / true") 为空。

    public static string ClientReturn(string ip, int port, string message)
    {
        string toReturn = "";
        BackgroundWorker worker = new BackgroundWorker();
        worker.DoWork += delegate (object s, DoWorkEventArgs args)
        {
            //---data to send to the server---
            string textToSend = message;

            //---create a TCPClient object at the IP and port no.---
            TcpClient client = new TcpClient(ip, port);
            NetworkStream nwStream = client.GetStream();
            byte[] bytesToSend = ASCIIEncoding.ASCII.GetBytes(textToSend);

            //---send the text---
            Console.WriteLine("Sending : " + textToSend);
            nwStream.Write(bytesToSend, 0, bytesToSend.Length);

            //---read back the text---
            byte[] bytesToRead = new byte[client.ReceiveBufferSize];
            int bytesRead = nwStream.Read(bytesToRead, 0, client.ReceiveBufferSize);
            toReturn = Encoding.ASCII.GetString(bytesToRead, 0, bytesRead);
            Console.WriteLine("Returned: " + toReturn); //It's the return of the server
            client.Close();
        };
        worker.RunWorkerAsync();
        return toReturn; //Return the value but not work it's return nothing
    }

问题是您没有等待 BackgroundWorker 完成。

老实说,BackgroundWorker反正已经过时了。而是使用 asyncawait.

您还缺少 using 块来处理客户端和流。

public static async Task<string> ClientReturn(string ip, int port, string textToSend)
{
    //---create a TCPClient object at the IP and port no.---
    using (TcpClient client = new TcpClient())
    {
        await client.ConnectAsync(ip, port);
        using (NetworkStream nwStream = client.GetStream())
        {
            byte[] bytesToSend = Encoding.ASCII.GetBytes(textToSend);

            //---send the text---
            Console.WriteLine("Sending : " + textToSend);
            await nwStream.WriteAsync(bytesToSend, 0, bytesToSend.Length);

            //---read back the text---
            byte[] bytesToRead = new byte[client.ReceiveBufferSize];
            int bytesRead = await nwStream.ReadAsync(bytesToRead, 0, client.ReceiveBufferSize);
            var toReturn = Encoding.ASCII.GetString(bytesToRead, 0, bytesRead);
            Console.WriteLine("Returned: " + toReturn); //It's the return of the server
            return toReturn; //Return the value but not work it's return nothing
        };
    }
}