当我使用form.ShowDialog

时间:2018-08-25 00:32:08

标签: multithreading winforms

MyForm myForm = new MyForm();
myForm.ShowDialog();

在MyFormClass中

private void MyForm_Load(object sender, EventArgs e)
        {
            nameLabel.Text = user.username;
            waitForServerMsgThread = new Thread(() => {
                Thread.CurrentThread.IsBackground = true;
                AddMessage("Start of this thread");
                try
                {
                    stream = client.GetStream();
                    while (true)
                    {
                        AddMessage(client.Available.ToString());
                        if (client.Available > 0)
                        {
                            byte[] byteToRead = new byte[client.Available];
                            stream.Read(byteToRead, 0, byteToRead.Length);
                            MessageToClient message = (MessageToClient)Commands.FromBytes(byteToRead);
                            if (message.messageType == MessageToClient.MessageType.IncoimgMessage)
                            {
                                MessageFromPerson msg = (MessageFromPerson)message.Message;
                                AddMessage(msg.name + " says: " + msg.msg);
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    AddMessage("Could not load data from server error " + ex.ToString());
                }
            });
            waitForServerMsgThread.Start();
            FormClosing += (s, args) => waitForServerMsgThread.Abort();
        }

无论将Thread.Start放在_Load还是按下按钮时,它甚至都不会执行线程。而且我无法使用myForm.Show();加载表单,因为它不会显示它将在我调用后关闭(ShowDialog()是从线程调用的)

0 个答案:

没有答案