如何在后台代码运行C#时使UI不冻结 [英] How do I make my UI not Freeze while background code is running C#

查看:76
本文介绍了如何在后台代码运行C#时使UI不冻结的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因此,我试图制作一个可以执行从客户端发送的功能的应用程序,它工作正常,但UI冻结,同时侦听来自客户端的消息时,我需要更改些什么才能使此代码运行Async?已经尝试将public void ExecuteServer(string pwd)更改为公共异步任务ExecuteServer(string pwd),但这只是告诉我即时通讯没有等待状态

So Im trying to make an app that can execute functions send from a client it works fine but the UI freezes while its listening for a message from a Client what do I have to change to make this code run Async? Already tried changing public void ExecuteServer(string pwd) to public async task ExecuteServer(string pwd) but it just tells me that im lacking an await

//Where im calling it
public Form2()
{
    InitializeComponent();
    (ExecuteServer("test"));
}

//The Network Socket im trying to run Async        
public static void ExecuteServer(string pwd)
{
    // Establish the local endpoint  
    // for the socket. Dns.GetHostName 
    // returns the name of the host  
    // running the application. 
    IPHostEntry ipHost = Dns.GetHostEntry(Dns.GetHostName());
    IPAddress ipAddr = ipHost.AddressList[0];
    IPEndPoint localEndPoint = new IPEndPoint(ipAddr, 11111);

    // Creation TCP/IP Socket using  
    // Socket Class Costructor 
    Socket listener = new Socket(ipAddr.AddressFamily,
                SocketType.Stream, ProtocolType.Tcp);

    try
    {
        // Using Bind() method we associate a 
        // network address to the Server Socket 
        // All client that will connect to this  
        // Server Socket must know this network 
        // Address 
        listener.Bind(localEndPoint);

        // Using Listen() method we create  
        // the Client list that will want 
        // to connect to Server 
        listener.Listen(10);
        while (true)
        {
            //Console.WriteLine("Waiting connection ... ");

            // Suspend while waiting for 
            // incoming connection Using  
            // Accept() method the server  
            // will accept connection of client 
            Socket clientSocket = listener.Accept();

            // Data buffer 
            byte[] bytes = new Byte[1024];
            string data = null;

            while (true)
            {
                int numByte = clientSocket.Receive(bytes);

                data += Encoding.ASCII.GetString(bytes,
                                        0, numByte);

                if (data.IndexOf("<EOF>") > -1)
                    break;
            }

            Console.WriteLine("Text received -> {0} ", data);
            if(data == "<EOF> " + "kill")
            {
                Application.Exit();
            } 
            else if (data == "<EOF>" + "getpw")
            {
                sendtoclient(clientSocket, pwd);
            } 
            else
            {
                sendtoclient(clientSocket, "Error 404 message not found!");
            }

            // Close client Socket using the 
            // Close() method. After closing, 
            // we can use the closed Socket  
            // for a new Client Connection 
            clientSocket.Shutdown(SocketShutdown.Both);
            clientSocket.Close();
        }
    }

    catch (Exception e)
    {
        //Console.WriteLine(e.ToString());
    }
}

推荐答案

在ExecuteServer的开头使用 await Task.Run(()=> {...}); {...} 中的代码.

Use await Task.Run(() => {...}); at the beginning of ExecuteServer and put its code inside {...}.

P.S.在使用上面的代码之前,如果您要使用UI中的任何组件,请将其属性插入变量中.像这样: var name = txtName.Text; 并使用变量.

P.S. Before using the above code, if you're usging any component from UI, insert it's property in a variable. Like this: var name = txtName.Text; and the use the variable.

这篇关于如何在后台代码运行C#时使UI不冻结的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆