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.

  • 相关阅读:
    面向对象的继承关系体现在数据结构上时,如何表示
    codeforces 584C Marina and Vasya
    codeforces 602A Two Bases
    LA 4329 PingPong
    codeforces 584B Kolya and Tanya
    codeforces 584A Olesya and Rodion
    codeforces 583B Robot's Task
    codeforces 583A Asphalting Roads
    codeforces 581C Developing Skills
    codeforces 581A Vasya the Hipster
  • 原文地址:https://www.cnblogs.com/timeObjserver/p/13751326.html
Copyright © 2011-2022 走看看