【问题标题】:Issue in opening a new GUI on second machine after first machine signals it在第一台机器发出信号后在第二台机器上打开新 GUI 的问题
【发布时间】:2015-06-16 06:34:24
【问题描述】:

我的两台 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);

代码在最后一行崩溃。

【问题讨论】:

    标签: c# winforms sockets


    【解决方案1】:

    似乎是“上下文”问题。

    当您的“新 GUI”(如您所指)表单被加载时,全局保持其上下文:

    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);
           ...
       }
    
    }
    

    【讨论】:

      猜你喜欢
      • 2015-01-01
      • 1970-01-01
      • 2018-11-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-10-16
      • 2017-03-31
      相关资源
      最近更新 更多