为什么不能更改客户端函数SignalR中的文本框文本

时间:2014-12-23 20:29:10

标签: asp.net textbox thread-safety signalr

我刚刚开始测试信号器,我试图在我从HUB类获得响应后将文本添加到富文本框中,但它不起作用(我的richtextbox中没有显示文本)我不知道为什么...(代码运行没有错误)

//服务器

public class ConnectByHub : Hub
    {
 public void testFunc(mas) {    
             string ans = mas + " got it";
            Clients.All.testFunc(ans);
        } }

//客户端

 private async void connectToServer()
        {
            Connection = new HubConnection(LocalClient);           
            HubProxy = Connection.CreateHubProxy("ConnectByHub");
            try
            {
                await Connection.Start();
            }
            catch (Exception ex)
            {                    
                return;
            }

            string msg = "Hello friend!";
            HubProxy.Invoke("testFunc", (msg)).Wait();
            // Option one - doesn't work
            HubProxy.On<string>("testFunc", (param) => Invoke((Action)(() => { MsgTxtBox.Text =         "something happened"; })));
            //Option two - doesn't work
            HubProxy.On<string>("testFunc", (param) => this.Invoke((Action)(() => { MsgTxtBox.AppendText("Something happend " + Environment.NewLine); })));

        }

1 个答案:

答案 0 :(得分:0)

我认为部分问题是尝试从运行侦听器的同一Async方法(connectToServer)发送消息。
我大多使用了问题中的相同代码,但提出了几个问题:

  • 将HubProxy.Invoke()移出Async方法并从button_click事件中调用它
  • 在参数
  • 上调用string.format()

SERVER:

     public class ConnectByHub : Hub
            {
                public void Send(string message)
                {
                    Clients.All.testFunc(message);
                }
            }

客户端:

      // Added button event
       private void button1_Click(object sender, EventArgs e)
            {
                string msg = "Hello friend!";
                HubProxy.Invoke("Send", msg).Wait();
            }


        private async void ConnectToServerAsync()
        {

            Connection = new HubConnection(LocalClient);
            HubProxy = Connection.CreateHubProxy("ConnectByHub");

            // Put the parmater in string.format()
            HubProxy.On<string>("testFunc", (param) => this.Invoke((Action)(() => MsgTxtBox.AppendText(string.Format("{0}", param)))));

            try
            {
                await Connection.Start();
            }
            catch (Exception ex)
            {
                richTextBox1.AppendText(string.Format("Unable to Connect to server ({0})", ServerURI));
                return;
            }

        }