Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice
  3. Join us on November 16th, 2023, between 1 pm and 9 pm CET for Ask the Experts Online on Discord and on Unity Discussions.
    Dismiss Notice

bool isInMainThread() Method?

Discussion in 'Editor & General Support' started by RKSandswept, Feb 20, 2014.

  1. RKSandswept

    RKSandswept

    Joined:
    Apr 26, 2013
    Posts:
    22
    I need to know if the current thread is the 'main' thread.
    like...
    Code (csharp):
    1.  
    2. public static bool isInMainThread()
    3. {
    4.      // What goes here??
    5. }
    6.  
    This is so I can have a loggin function that
    uses Time.time.ToString() which can only be used in the main thread, and not use Time.time if not in the mian thread.
     
  2. Deleted User

    Deleted User

    Guest

    ? I dont get what you want to do here ...
    If you have created a thread on your own than this thread will never be "in the main thread".
     
  3. Eric5h5

    Eric5h5

    Volunteer Moderator Moderator

    Joined:
    Jul 19, 2006
    Posts:
    32,401
    Right...everything is already in the main thread by default. If you do your own threads then you already know if you're using the main thread or not and thus don't need any function to tell you.

    --Eric
     
  4. siddartha_

    siddartha_

    Joined:
    Apr 17, 2013
    Posts:
    11
    Yeah, right, whatever.
    Anyway, if the OP or any visitor is still interested, this is how I do it:
    I do this in a static class called App:

    Code (CSharp):
    1. using System.Threading;
    2.  
    3. public static class App
    4. {
    5.     public static int unityThreadId = -1;
    6.  
    7.     public static bool IsUnityThread()
    8.     {
    9.         return (Thread.CurrentThread.ManagedThreadId == unityThreadId);
    10.     }
    11. }

    So right at the very beginning of your game, in the Awake() of a global component or something, you do something like:

    Code (CSharp):
    1. App.unityThreadId = Thread.CurrentThread.ManagedThreadId;
    then you can just call App.IsUnityThread() anytime.
    Beware! This will not work in the Editor! For some strange reason I don't understand, ManagedThreadId *always* returns 1, no matter what thread your in, when called inside the editor. It will work on builds no problem, though.