Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 6955437
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 27, 20262026-05-27T14:44:10+00:00 2026-05-27T14:44:10+00:00

I have some trouble with threading in my application. I have a multi-threaded client/server

  • 0

I have some trouble with threading in my application. I have a multi-threaded client/server application. I’m also using C# MonoDevelop for Unity3d. Not sure if it makes any difference for the answer. I’ll try to explain where my problem is:

Unity works on a single thread. So if i want to instantiate an object which uses the abstract class ScriptableObject from unity, then this must be done on the main thread on which Unity runs.

But my server socket spawns a thread for every connected client, so that incoming data can be processed async. The received data is processed in the OnDataReceived() method (which runs on its own thread)

The problem here is, is that i can’t create an instance of a Player object inside the OnDataReceived() thread. Because my Player object inherits from ScriptableObject. Which means this object should be created on the main Unity thread.

But i have no idea how to do that… Is there a way to switch back to the main thread, so i can still create a Player object in the OnDataReceived() method?

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-27T14:44:10+00:00Added an answer on May 27, 2026 at 2:44 pm

    .NET already has a concept of a SynchronizationContext, most often used for UI apps where thread affinity is required to invoke operations on UI controls (e.g. in WPF or WinForms). However, even outside a UI app, you can reuse these concepts for a general purpose thread-affinitized work queue.

    This sample shows how to use the WPF DispatcherSynchronizationContext (from WindowsBase.dll) in a simple console application, together with the .NET 4.0 task classes (TaskScheduler / Task) to invoke actions originating on child threads back on the main program thread.

    using System;
    using System.Threading;
    using System.Threading.Tasks;
    using System.Windows.Threading;
    
    internal sealed class Program
    {
        private static void Main(string[] args)
        {
            int threadCount = 2;
            using (ThreadData data = new ThreadData(threadCount))
            {
                Thread[] threads = new Thread[threadCount];
                for (int i = 0; i < threadCount; ++i)
                {
                    threads[i] = new Thread(DoOperations);
                }
    
                foreach (Thread thread in threads)
                {
                    thread.Start(data);
                }
    
                Console.WriteLine("Starting...");
    
                // Start and wait here while all work is dispatched.
                data.RunDispatcher();
            }
    
            // Dispatcher has exited.
            Console.WriteLine("Shutdown.");
        }
    
        private static void DoOperations(object objData)
        {
            ThreadData data = (ThreadData)objData;
            try
            {
                // Start scheduling operations from child thread.
                for (int i = 0; i < 5; ++i)
                {
                    int t = Thread.CurrentThread.ManagedThreadId;
                    int n = i;
                    data.ExecuteTask(() => SayHello(t, n));
                }
            }
            finally
            {
                // Child thread is done.
                data.OnThreadCompleted();
            }
        }
    
        private static void SayHello(int requestingThreadId, int operationNumber)
        {
            Console.WriteLine(
                "Saying hello from thread {0} ({1}) on thread {2}.",
                requestingThreadId,
                operationNumber,
                Thread.CurrentThread.ManagedThreadId);
        }
    
        private sealed class ThreadData : IDisposable
        {
            private readonly Dispatcher dispatcher;
            private readonly TaskScheduler scheduler;
            private readonly TaskFactory factory;
            private readonly CountdownEvent countdownEvent;
    
            // In this example, we initialize the countdown event with the total number
            // of child threads so that we know when all threads are finished scheduling
            // work.
            public ThreadData(int threadCount)
            {
                this.dispatcher = Dispatcher.CurrentDispatcher;
                SynchronizationContext context = 
                    new DispatcherSynchronizationContext(this.dispatcher);
                SynchronizationContext.SetSynchronizationContext(context);
                this.scheduler = TaskScheduler.FromCurrentSynchronizationContext();
                this.factory = new TaskFactory(this.scheduler);
                this.countdownEvent = new CountdownEvent(threadCount);
            }
    
            // This method should be called by a child thread when it wants to invoke
            // an operation back on the main dispatcher thread.  This will block until
            // the method is done executing.
            public void ExecuteTask(Action action)
            {
                Task task = this.factory.StartNew(action);
                task.Wait();
            }
    
            // This method should be called by threads when they are done
            // scheduling work.
            public void OnThreadCompleted()
            {
                bool allThreadsFinished = this.countdownEvent.Signal();
                if (allThreadsFinished)
                {
                    this.dispatcher.InvokeShutdown();
                }
            }
    
            // This method should be called by the main thread so that it will begin
            // processing the work scheduled by child threads. It will return when
            // the dispatcher is shutdown.
            public void RunDispatcher()
            {
                Dispatcher.Run();
            }
    
            public void Dispose()
            {
                this.Dispose(true);
                GC.SuppressFinalize(this);
            }
    
            // Dispose all IDisposable resources.
            private void Dispose(bool disposing)
            {
                if (disposing)
                {
                    this.countdownEvent.Dispose();
                }
            }
        }
    }
    

    Sample output:

    Starting...
    Saying hello from thread 3 (0) on thread 1.
    Saying hello from thread 4 (0) on thread 1.
    Saying hello from thread 3 (1) on thread 1.
    Saying hello from thread 4 (1) on thread 1.
    Saying hello from thread 3 (2) on thread 1.
    Saying hello from thread 4 (2) on thread 1.
    Saying hello from thread 3 (3) on thread 1.
    Saying hello from thread 4 (3) on thread 1.
    Saying hello from thread 3 (4) on thread 1.
    Saying hello from thread 4 (4) on thread 1.
    Shutdown.
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have some trouble using Tomcat Client Deployer (TCD) with a local Tomcat installation.
I have some trouble with jquery ui-events: In my application, there are some sliders.
I have some trouble achieving adequate real-time performance from my application and wondering if
i am using c++ and i have some trouble about pointers i know that
I have some trouble with dbus-send when using a{sv} Calling a method with in_signature='a{ss}'
I have some trouble using the Zend url helper with get parameter. In a
I have some trouble with using authlogic in my rails app, so I began
I have some trouble using decltype for member function pointers: #include <iostream> #include <type_traits>
I have some trouble reading from an ini file using boost program options. The
I'm building a monitor app and am having some threading issues. I have, using

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.