简体   繁体   中英

How to run delegate method on main thread that was invoked on a separated thread?

I wish to run onSomeEvent() on main thread because I plan to access Clipboard , which can only be done within main thread. If possible, I wish to do it as console application. I know I could make a WPF and wrap the calls in Control.Invoke() but I prefer not to use whole framework simply to move a method call between 2 threads. I made a simplified example below:

   public static class Listener {
      public static event Action onSomeEvent;
      public static void Run() {
         onSomeEvent?.Invoke();
      }
   }

   public class Program {

      public static void Main(string[] args) {
         Console.WriteLine("Main thread id: " + Thread.CurrentThread.ManagedThreadId);
         Listener.onSomeEvent += () => {
            Console.WriteLine("onSomeEvent's ManagedThreadId: " + Thread.CurrentThread.ManagedThreadId);
         };

         Thread spawn = new Thread(() => {
            Console.WriteLine("spawned thread's ManagedThreadId: " + Thread.CurrentThread.ManagedThreadId);
            Thread.Sleep(1000);
            Listener.Run();

         });
         spawn.Start();

         Console.ReadLine();
      }
   }

You can send your Main thread into a blocking read loop on a queue of Tasks. Like this:

class Program
{
    public static BlockingCollection<Task> MainThreadTasks = new BlockingCollection<Task>();
    static void Main(string[] args)
    {
        Console.WriteLine($"Running on Main thread {Thread.CurrentThread.ManagedThreadId}");

        ThreadPool.QueueUserWorkItem((o) =>
            {
                var t = new Task(() => Console.WriteLine("Do Sometihg"));
                MainThreadTasks.Add(t);
                t.Wait();
            }
        );


        while (true)
        {
            Console.WriteLine("Main thread waiting Task");
            var task = MainThreadTasks.Take();

            Console.WriteLine("Main thread running Task");
            task.RunSynchronously();
            Console.WriteLine("Main thread finished Task");
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM