Notify when thread is complete, without locking calling thread

后端 未结 7 1310
既然无缘
既然无缘 2020-12-15 09:13

I am working on a legacy application that is built on top of NET 3.5. This is a constraint that I can\'t change. I need to execute a second thread to run a long running tas

7条回答
  •  情话喂你
    2020-12-15 09:27

    1. A very simple thread of execution with completion callback
    2. This does not need to run in a mono behavior and is simply used for convenience
    using System;
    using System.Collections.Generic;
    using System.Threading;
    using UnityEngine;
    
    public class ThreadTest : MonoBehaviour
    {
        private List numbers = null;
    
        private void Start()
        {
            Debug.Log("1. Call thread task");
    
            StartMyLongRunningTask();
    
            Debug.Log("2. Do something else");
        }
    
        private void StartMyLongRunningTask()
        {
            numbers = new List();
    
            ThreadStart starter = myLongRunningTask;
    
            starter += () =>
            {
                myLongRunningTaskDone();
            };
    
            Thread _thread = new Thread(starter) { IsBackground = true };
            _thread.Start();
        }
    
        private void myLongRunningTaskDone()
        {
            Debug.Log("3. Task callback result");
    
            foreach (int num in numbers)
                Debug.Log(num);
        }
    
    
        private void myLongRunningTask()
        {
            for (int i = 0; i < 10; i++)
            {
                numbers.Add(i);
    
                Thread.Sleep(1000);
            }
        }
    }
    

提交回复
热议问题