从多个后台线程同步wpf dispatcher.invoke

时间:2022-08-28 07:39:12

Do I need to synchronize calls to the Dispatcher.Invoke if accessing from multiple background threads?

如果从多个后台线程访问,是否需要同步对Dispatcher.Invoke的调用?

I know the Dispatcher.BeginInvoke automatically synchronizes calls for silverlight app (http://msdn.microsoft.com/en-us/library/z8chs7ft(v=vs.95).aspx)

我知道Dispatcher.BeginInvoke会自动同步对silverlight app的调用(http://msdn.microsoft.com/en-us/library/z8chs7ft(v=vs.95).aspx)

Is it also true for a wpf application or should I uncomment the lock statement below.

对于wpf应用程序也是如此,或者我应该取消注释下面的lock语句。

  public MainWindow()
    {
        InitializeComponent();

        Dispatcher.BeginInvoke(new Action(() =>
            {
                const int MAX_NR_THREADS = 1000;
                for (int i = 0; i < MAX_NR_THREADS; ++i)
                {
                    int j = i+1;
                    new Thread(()=>ThreadMethod(j)).Start();
                }
            }));
    }


    private void ThreadMethod(int threadId)
    {
        const int ONE_MILLION = 1000000;
        for (int i = 0; i < ONE_MILLION/threadId; ++i)
        {            

            //lock(lockObj)
            //{                   
                this.Dispatcher.Invoke(new Action(() =>
                    {
                        int sum = 0;
                        for (int j = 0; j < ONE_MILLION/10000; ++j)
                        {
                            sum += j;
                        }
                        int a = sum;
                        concurrentQueue.Enqueue(threadId*ONE_MILLION);                    
                    }));                    
            //}                
        }
    }

1 个解决方案

#1


6  

There is no need to synchronize these calls. Dispatcher.Invoke effectively acts as a queue for your calls already, and doesn't require synchronization.

无需同步这些调用。 Dispatcher.Invoke已经有效地充当您的调用队列,并且不需要同步。

#1


6  

There is no need to synchronize these calls. Dispatcher.Invoke effectively acts as a queue for your calls already, and doesn't require synchronization.

无需同步这些调用。 Dispatcher.Invoke已经有效地充当您的调用队列,并且不需要同步。