c# - 在主线程中运行代码

标签 c# wpf multithreading winforms thread-safety

它类似于许多问题,但不是 rly。我需要像 BeginInvoke 这样的东西用于 Winforms,但不仅仅用于 winforms。所以我需要单一的方法,适用于任何类型的应用程序,所以我打电话

void ExecuteInMainContext(Action action)
{
   ...
}

它应该可以工作,可以从控制台、winforms、wpf 等调用。我看到的所有方法都是对 winforms 使用 BeginInvoke,对 WPF 等使用 Dispatcher.Invoke。但我应该从库中调用它,但我不知道从哪里调用它。而且它对调用代码也应该是透明的,所以它不应该传递诸如指针之类的东西来调用主线程等,lib 应该从环境中获取此信息,而不是从用户代码中获取,当然没有任何全局变量。

我试过使用 Task.ConfigureAwait,但没有用。

我找到了这个

You can't do this (without a lot of work) in a Console application. The mechanisms built into the TPL for marshaling the call back onto a thread all rely on the thread having an installed SynchronizationContext. This typically gets installed by the user interface framework (ie: Application.Run in Windows Forms, or in WPF's startup code, etc).

但我希望这是可能的。

测试代码:

using System;
using System.Threading;

namespace Test
{
    class Program
    {
        private static void Main(string[] args)
        {

            Console.WriteLine("Main: " + Thread.CurrentThread.ManagedThreadId);
            Publisher publisher = new Publisher(Method);
            Console.ReadLine();
        }

        private static void Method(string s)
        {
            Console.WriteLine(s + " " + Thread.CurrentThread.ManagedThreadId);
        }

    }

    class Publisher
    {
        public event Action<string> Action;

        protected virtual void OnAction(string obj)
        {
            Action<string> handler = Action;
            if (handler != null)
            {
                SafeCall(() => handler(obj));
            }
        }

        private static void SafeCall(Action action)
        {
            // ???
            action(); // should write 1
        }

        public Publisher(Action<string> action)
        {
            Action = action;
            Console.WriteLine("Publisher thread: " + Thread.CurrentThread.ManagedThreadId);
            Thread thread = new Thread(() => OnAction("hello"));
            thread.Start();
        }
    }
}

所以它应该在任何地方写相同的数字。

最佳答案

试试这个

void ExecuteInMainContext(Action action)
    {
        var synchronization = SynchronizationContext.Current;
        if (synchronization != null)
        {
            synchronization.Send(_ => action(), null);//sync
            //OR
            synchronization.Post(_ => action(), null);//async
        }
        else
            Task.Factory.StartNew(action);

        //OR
        var scheduler = TaskScheduler.FromCurrentSynchronizationContext();

        Task task = new Task(action);
        if (scheduler != null)
            task.Start(scheduler);
        else
            task.Start();
    }

关于c# - 在主线程中运行代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20300164/

相关文章:

c# - 绑定(bind)一个枚举

wpf - Visual Studio 2010 中的 prism 项目链接器发生了什么变化?

c - c语言在多线程应用中clock()是如何计时的?

c - 我怎样才能阻塞线程直到找到素数,解除阻塞,然后让它们等到下一个素数?

c# - Oracle 和 SQL Server 之间的多线程数据传输 - 网络性能

c# - 如何为 Windows 应用商店应用程序创建自定义按钮?

c# - 在C#中,整数文字是什么类型?

c# - ASP.NET MVC 2 博客文章似乎在讨论不存在的属性

c# - 如何在C#中实现真正的函数管道?

c# - 如何将击键发送到 WebBrowser?