質問

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

I know the Dispatcher.BeginInvoke automatically synchronizes calls for 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.

  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);                    
                    }));                    
            //}                
        }
    }
役に立ちましたか?

解決

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

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top