LoginSignup
7
7

More than 5 years have passed since last update.

Unity C# スレッドの休止と再開

Last updated at Posted at 2015-04-24

AutoResetEvent クラス

上記クラスを使ってスレッドの休止と再会を管理

参考URL:
 http://okwakatta.net/topic/topic025.html
 http://www.wisdomsoft.jp/526.html

スレッド呼び出し元、Unityエディタからクリックイベントで呼ばれる

ThreadCallBase
using UnityEngine;
using System.Collections;
using UnityEngine.UI;

public class ThreadCallBase : MonoBehaviour {

    private Thread1 ThreadOne = new Thread1();
    public Text LogText;

    // Use this for initialization
    void Start () {

        ThreadOne.ThreadStart();
    }



    public void OnclickThreadSleep()
    {
        ThreadOne.SleepFlgTrue();
        Debug.Log(ThreadOne.TestString);
        LogText.text = ThreadOne.TestString;
    }


    public void OnclickThreadInterupt()
    {
        ThreadOne.SleepFlgFalse();
        Debug.Log(ThreadOne.TestString);
        LogText.text = ThreadOne.TestString;

    }


    public void OnclickLog()
    {
        Debug.Log(ThreadOne.TestString);
        LogText.text = ThreadOne.TestString;

    }

    // This function is called when the MonoBehaviour will be destroyed (Since v3.2)
    public void OnDestroy()
    {
        ThreadOne._threadFirst.Interrupt();
        ThreadOne._threadEvent.Reset();
    }
}

スレッド側ソース Unity関係のものは一切使えない

Thread1
using UnityEngine;
using System.Collections;
using System.Threading;

public class Thread1  {


    public Thread _threadFirst;

    public AutoResetEvent _threadEvent;

    public string TestString;

    public bool sleepFLG = false;

    public void ThreadStart()
    {
        sleepFLG = false;
        _threadFirst = new Thread(ThreadWorking);
        _threadEvent = new AutoResetEvent(true);
        _threadFirst.Start();
    }


    public void ThreadWorking()
    {
        while(true){

            if (sleepFLG == true)
            {
                TestString = "Sleep On";
                // スレッドを休止状態にする。
                _threadEvent.WaitOne();
            }
            else
            {
                TestString = "Sleep Off";
            }
        }
    }


    public void SleepFlgFalse()
    {
        /* スレッド処理を実行するようにフラグを落とします */
        sleepFLG= false;

        /* AutoResetEventオブジェクトをシグナル状態にして
            スレッドを再開させます */
        _threadEvent.Set();
    }

    public void SleepFlgTrue()
    {
        sleepFLG = true;
    }
}
7
7
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
7
7