Qiita Teams that are logged in
You are not logged in to any team

Log in to Qiita Team
Community
OrganizationEventAdvent CalendarQiitadon (β)
Service
Qiita JobsQiita ZineQiita Blog
7
Help us understand the problem. What are the problem?

More than 5 years have passed since last update.

@satotin

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

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;
    }
}
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
7
Help us understand the problem. What are the problem?