在第一台机器发出信号后,在第二台机器上打开新GUI的问题

时间:2015-06-16 06:34:25

标签: c# winforms sockets

我在我的两台Windows机器上都运行了一个GUI应用程序(c#中的windows窗体)。两台机器通过套接字(异步)相互连接。 服务器(第二台机器)处于聆听模式。 当用户按下客户端(第一台机器)上的按钮时,客户端机器自己打开一个新的GUI应用程序,并向服务器机器发出信号。

现在,我在服务器机器上遇到了问题。 如果我使用 Form.Show(),我无法在新的GUI上执行任何操作。 如果我使用 Form.ShowDialog(),那么在这种情况下,一旦我关闭新的GUI,我的主应用程序就会在服务器机器上崩溃。 在客户端计算机上未观察到此问题。

以下是服务器机器的代码:

    public static void ReadCallback(IAsyncResult ar)
    {
        try
        {
            String content = String.Empty;
            StateObject state = (StateObject)ar.AsyncState;
            Socket handler = state.workSocket;
            int bytesRead = handler.EndReceive(ar);
            if (bytesRead > 0)
            {
                // There  might be more data, so store the data received so far.
                    state.sb.Append(Encoding.ASCII.GetString(
                    state.buffer, 0, bytesRead));

                // Check for end-of-file tag. If it is not there, read 
                // more data.
                content = state.sb.ToString();
                Logger.DebugLogFile(content);
                if (content.IndexOf("<EOF>") > -1)
                {
                    if (content.IndexOf("start") > -1)
                    {
                            Tool_Logging tl = new Tool_Logging();
                            tl.ShowDialog();
                            Send(handler, "<EOF>");
                            Thread.Sleep(100);
                            listener.BeginAccept(
                    new AsyncCallback(AcceptCallback),
                    listener);

代码在最后一行崩溃。

1 个答案:

答案 0 :(得分:0)

似乎是一个&#39; Context&#39;问题。

当你的新GUI&#39; (正如你所指的那样)加载表格,保持其全局背景:

public class NewGUIForm : Form
{
    static System.Threading.SynchronizationContext _context = null;

    ... 

    protected override void OnLoad(EventArgs e)
    {
        _context = WindowsFormsSynchronizationContext.Current;
        base.OnLoad(e);
    }

    ...

   public static void ReadCallback(IAsyncResult ar)
   {
       ...
       System.Threading.SendOrPostCallback method = new System.Threading.SendOrPostCallback((o) =>
                {
                        Tool_Logging tl = new Tool_Logging();
                        tl.ShowDialog();
                });
       _context.Post(method, input);
       ...
   }

}