美文网首页
不要在协程里做耗时的工作,会卡住整个游戏

不要在协程里做耗时的工作,会卡住整个游戏

作者: jojo911 | 来源:发表于2019-08-12 16:55 被阅读0次

    以下是测试代码,分别用线程和协程实现

    using System.Collections;
    using System.Collections.Generic;
    using System.IO;
    using System.Threading;
    using UnityEngine;
    using UnityEngine.UI;
    
    public class CoroutinTest : MonoBehaviour
    {
        public Text t;
        int m_Count = 0;
        float m_second = 0;
        // Use this for initialization
        void Start ()
        {
            //StartCoroutine(CoroutineTest());
    
            new Thread(new ThreadStart(SubThread)).Start();
        }
    
        private void Update()
        {
            t.text = m_Count.ToString() + " " + m_second;
        }
    
        void SubThread()
        {
            while (true)
            {
                Thread.Sleep(1000);
    
                string strFile = "E:/MyTest/Unity2017/Assets/ColoutineTest.txt";
    
                //Debug.Log(string.Format("begin time : {0}", System.DateTime.Now.ToString("T")));
    
                long tmp = System.DateTime.Now.Ticks;
    
                for (int i = 0; i < 100; i++)
                {
                    byte[] b = File.ReadAllBytes(strFile);
                }
    
                m_second = (System.DateTime.Now.Ticks - tmp) / 1000000;
    
                //Debug.Log(string.Format("end time : {0}", System.DateTime.Now.ToString("T")));
    
                m_Count++;
            }
        }
    
        IEnumerator CoroutineTest()
        {
            while (true)
            {
                yield return new WaitForSeconds(1f);
    
                string strFile = "E:/MyTest/Unity2017/Assets/ColoutineTest.txt";
    
                Debug.Log(string.Format("begin time : {0}", System.DateTime.Now.ToString("T")));
    
                long tmp = System.DateTime.Now.Ticks;
    
                for (int i = 0; i < 100; i++)
                {
                    byte[] b = File.ReadAllBytes(strFile);
                }
    
                m_second = (System.DateTime.Now.Ticks - tmp) / 1000000;
    
                Debug.Log(string.Format("end time : {0} tick:{1}", System.DateTime.Now.ToString("T"), m_second));
    
                m_Count++;
            }
        }
    }
    
    

    相关文章

      网友评论

          本文标题:不要在协程里做耗时的工作,会卡住整个游戏

          本文链接:https://www.haomeiwen.com/subject/yvnujctx.html