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

C# Delegate + Multithreading

Discussion in 'Scripting' started by SlayerOfGod, Mar 9, 2014.

  1. SlayerOfGod

    SlayerOfGod

    Joined:
    Sep 22, 2012
    Posts:
    8
    Hi, im having problem with delegate not firing.

    Basically, im using delegate for a client -> server communication.

    Client register to delegate.
    Client send message

    Server process message
    Server send response

    Listening thread fire invoke

    I added a basic sequence diagram of what im trying to explain.
    $Sequence Diagram1.jpg

    The problem is when i invoke the delegate, i have a null error.
    Im guessing its because background thread can't invoke listener from the mainThread.

    So i tried BeginInvoke.
    But now im getting this error when trying to set a TextMesh text :
    set_text can only be called from the main thread.
    Constructors and field initializers will be executed from the loading thread when loading a scene.
    Don't use this function in the constructor or field initializers, instead move initialization code to the Awake or Start function.


    Is there a way i can 'redirect' the invoke from backgroundThread to mainThread?

    Ty!!!
     
  2. justinlloyd

    justinlloyd

    Joined:
    Aug 5, 2010
    Posts:
    1,680
    Unfortunately in Unity any function of signifigance requires it to run on the main thread. There's a couple of alternatives but your best bet is the thread synchronization methods built-in to .NET. There are also a few 3rd-party libraries such as ConcurrentQueue and HashBucket that will let you queue up actions or objects for processing on a different thread.

    If you just want to setText, i.e. uni-directional updating, you could use a thread synchronization lock to set a string property in an object running on your communication thread, then call the actual setText from the main thread when it detects that the string has changed using a semaphore or mutex trigger.

    BeginInvoke, whilst powerful, is unfortunately not a panacea to your threading woes.
     
  3. SlayerOfGod

    SlayerOfGod

    Joined:
    Sep 22, 2012
    Posts:
    8
    Ty for you're reply. No im not just using setText. I want to use this for my core structure for any server request.
    Is it possible to give me an example of how i can queue up action on another thread? This would solve my problem!
     
  4. SlayerOfGod

    SlayerOfGod

    Joined:
    Sep 22, 2012
    Posts:
    8