zoukankan      html  css  js  c++  java
  • 多线程中使用UNITY变量导致线程执行断掉却又不报错的问题

    时间:2020.9.29,XMoba第一次Demo

    子线程调用UNITY的相关变量或函数导致程序执行过程断掉,且不报任何错误的一个BUG

    一,问题现象

    网络异步连接的回调函数中使用了一个函数XLog.log,此函数中使用了UNITY的Time.FrameCount,导致程序执行到这一行时异常退出,但不报任何错误。

       

        void OnConnectCallback(IAsyncResult iar)
        {
            netState = XNetState.ConnectReturn;
    
            var info = tcpClient.Connected ? $"【服务器连接成功】" : $"【服务器连接失败】";
            XLog.Log(E_LogModule.Net, $"{info}, {curIp},{curPort},{netState}");
    
            try
            {
                tcpClient.EndConnect(iar);
                if (tcpClient.Connected)
                {
                    tcpClient.GetStream().BeginRead(tempBuffer, 0, tempBuffer.Length, OnReceiveCallback, null); //开始接收
                }
            }
            catch (Exception e)
            {
                UnityEngine.Debug.LogError($"【网络接收出错】{curIp},{curPort},{e}");
            }
        }

    二,解决方案

    将整个回调函数内部包在try-catch中,确保异常不会静默发生,如下

        void OnConnectCallback(IAsyncResult iar)
        {
            try
            {
                netState = XNetState.ConnectReturn;
    
                var info = tcpClient.Connected ? $"【服务器连接成功】" : $"【服务器连接失败】";
                XLog.Log(E_LogModule.Net, $"{info}, {curIp},{curPort},{netState}");
    
                tcpClient.EndConnect(iar);
                if (tcpClient.Connected)
                {
                    tcpClient.GetStream().BeginRead(tempBuffer, 0, tempBuffer.Length, OnReceiveCallback, null); //开始接收
                }
            }
            catch (Exception e)
            {
                UnityEngine.Debug.LogError($"【网络接收出错】{curIp},{curPort},{e}");
            }
        }

    三,这样处理后就能在运行捕获到UNITY的报错,如下:

     [Net]  错误:【网络接收出错】10.24.1.194,21010,UnityEngine.UnityException: get_frameCount can only be called from the main thread.

  • 相关阅读:
    用css画三角形(提示框三角形)
    SpringMVC(2)之表单(非表单)参数绑定
    mvn jetty:run--编码GBK的不可映射字符
    Git命令及常见问题
    eclipse整合ssh框架基础
    css基础一(权重与position)
    sublime Text3下sass环境配置(windows)
    sublime Text3 设置多个浏览器预览
    初识iOS NSTimer 循环引用不释放问题
    ARC MARC 文件支持
  • 原文地址:https://www.cnblogs.com/timeObjserver/p/13751326.html
Copyright © 2011-2022 走看看