C#如何从单独的类和线程中的静态方法更改textbox.text



所以我遇到的问题是我要在form1上设置textbox.text。我很快就发现了有关线程安全的问题,我认为我已经解决了该问题的代码。我遇到的下一个问题是,对客户的编码方式进行编码的方式必须是静态的,我想不到如何做。当然,除非我的客户方法在异常类中的方法不一定是静态的,否则是这样,并且由于我缺乏知识而造成的。

我可能会从Microsoft重新使用该模板为客户端说明。这主要是由于我是一名大学生,并且只是在使用它来学习。

如果这个问题已经存在,我也想提前道歉,但是当我看时,我找不到足够特定的问题。

这是代码的顶部减去名称空间。我会稍微将其分开,只是为了专注于我所说的部分。

    public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }
    Socket client;
    public delegate void setTextCallback(string text);
    public void setText(string text)
    {
        if (this.txtLog.InvokeRequired)
        {
            // Different thread, use Invoke.
            setTextCallback d = new setTextCallback(FinishSetText);
            this.Invoke(d, new object[] { text });
        }
        else
        {
            // Same thread, no Invoke.
            this.txtLog.Text = this.txtLog.Text + text;
        }
    }
    private void FinishSetText(string text)
    {
        this.txtLog.Text = this.txtLog.Text + text;
    }

上面是关于错误解决的代码,我遇到的交叉踏板问题。如果有一种更好的方法,我会尝试尝试新事物。

    // State object for receiving data from remote device.  
    public class StateObject
    {
        // Client socket.  
        public Socket workSocket = null;
        // Size of receive buffer.  
        public const int BufferSize = 256;
        // Receive buffer.  
        public byte[] buffer = new byte[BufferSize];
        // Received data string.  
        public StringBuilder sb = new StringBuilder(); 
    }
    public class AsyncClient
    {
        // The port number for the remote device.  
        private const int port = 8080;
        // ManualResetEvent instances signal completion.  
        private static ManualResetEvent connectDone =
            new ManualResetEvent(false);
        private static ManualResetEvent sendDone =
            new ManualResetEvent(false);
        private static ManualResetEvent receiveDone =
            new ManualResetEvent(false);
        public struct properties
        {
            public static String response { get; set; }
        }
        public static Socket StartClient()
        {
            IPAddress ipAddress = IPAddress.Parse("127.0.0.1");
            // Create a TCP/IP socket.  
            Socket client = new Socket(ipAddress.AddressFamily,
                SocketType.Stream, ProtocolType.Tcp);
            // Connect to a remote device.  
            try
            {
                // Establish the remote endpoint for the socket.  
                IPEndPoint remoteEP = new IPEndPoint(ipAddress, port);
                // Connect to the remote endpoint.  
                client.BeginConnect(remoteEP,
                    new AsyncCallback(ConnectCallback), client);
                connectDone.WaitOne();
                // Release the socket.  
                client.Shutdown(SocketShutdown.Both);
                client.Close();
                return client;
            }
            catch (Exception e)
            {
                setText(e.ToString()); 
                return client;
            }
        }
        private static void ConnectCallback(IAsyncResult ar)
        {
            try
            {
                // Retrieve the socket from the state object.  
                Socket client = (Socket)ar.AsyncState;
                // Complete the connection.  
                client.EndConnect(ar);
                setText(string.Format("Socket connected to {0}",
                    client.RemoteEndPoint.ToString()));
                // Signal that the connection has been made.  
                connectDone.Set();
            }
            catch (Exception e)
            {
                setText(e.ToString());
            }
          //Other AsyncClient methods below.
        }

在代码底部的上方您可以看到我要使用Form1的方法设置文本的位置,但是您还可以看到方法是静态的,这意味着它期望该方法的静态版本,这意味着使用This.textbox't不再工作,或者至少这是我对正在发生的事情的理解。任何帮助将不胜感激。

删除static关键字,然后将此代码添加到AsyncClient类的开始:

public class AsyncClient
{
    private Action<string> setText;
    public AsyncClient(Action<string> setText)
    {
        this.setText = setText;
    }

然后,当您从表单创建一个实例时,只需执行var ac = new AsyncClient(setText)并致电ac.StartClient()

最新更新