c# - 如何将矢量格式的图形从一个线程返回到另一个线程?

标签 c# wpf multithreading vector-graphics

我正在设计一个系统,其中有多个并行运行的任务。他们每个人都得到一些输入,并且应该以矢量格式返回图形输出。

然后,主 WPF 应用程序应根据用户请求绘制任何这些任务的结果。目前我使用 Canvas、Rectangle 和其他 System.Windows.Shapes 作为我的图形矢量格式作为输出。任务完成后,我获取 Canvas 子项,并将它们一个接一个地添加到 GUI 实际 Canvas 中。

但是,我刚刚发现 UI 元素不能在主线程(所谓的 Dispatcher 线程)以外的任何其他线程上创建。 http://social.msdn.microsoft.com/Forums/ar/wpf/thread/c4600372-342c-4ee4-b49c-d9abf967fc93
将 UI 元素的创建(如上文中所建议的)委托(delegate)给主线程对我来说不是一个选项,因为它们应该在用户请求输出时显示,而不是在任务完成时显示。

实际上我不需要在另一个线程中创建 UI 元素,我只需要一种方便的方法来创建矢量图形并稍后在 WPF 应用程序中显示它们。

有谁知道该怎么做?

最佳答案

在开始并行事件之前捕获 UI(主线程)的 SynchronizationContext。并在捕获的 SynchronizationContext 引用上调用(无论何时需要)Send 方法,以便将消息推送到 UI 线程。 MSDN on SynchronizationContext

public partial class MainWindow : Window
    {
        SynchronizationContext UISyncContext;
        YourTaskOutPut Myresult;
        public MainWindow()
        {
            InitializeComponent();
        }
        public StartProcessingVGraphics()
        {
            //Let say this method is been called from UI thread. i.e on a button click
            //capture the current synchronization context

            UISyncContext=TaskScheduler.FromCurrentSynchronizationContext;

            //Start your VGraph processing using TPL in background and store result to Myresult (of type YourTaskOutPut)
            result= GetMeTaskResults();

        }

        public GetMeResultNow()
        {
            //Let's say this is is the method which user triggers at
            //some point in time ( with the assumption that we have Myresult in hand)

            if(UISyncContext!=null)
                UISyncContext.Send(new SendOrPostCallback(delegate{ PutItInUI }),null);

            //Use Send method - to send your request synchronously
            //Use Post method- to send your request asynchronously
        }
        void PutItInUI()
        {
            //this method help you to put your result in UI/controls
        }

关于c# - 如何将矢量格式的图形从一个线程返回到另一个线程?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7876752/

相关文章:

c# - “Strange” C#属性语法

c# - C# 中的事件驱动标准输入

c# - MVVM:在 WPF NET 3.5 中完成线程池工作项后更新 View 的控件可见性

c# - DateTimePicker 日历默认为上次选择的月份/年份

c# - 在 WPF 中快速删除(和添加)许多项目到 Canvas

c# - .NET Core 中是否有等效于 DllImport 的 Linux?

wpf - WPF DataGrid 如何让卡住的行/列工作?

android - 如何终止 HandlerThreads?

c++ - 多个条件变量: threads out of sync problem

c# - P-Linq 可以在委托(delegate)执行期间切换线程吗?