如果从多个后台线程访问,是否需要同步对 Dispatcher.Invoke 的调用?
我知道 Dispatcher.BeginInvoke 自动同步对 silverlight 应用程序的调用(http://msdn.microsoft.com/en-us/library/z8chs7ft(v=vs.95).aspx)
对于 wpf 应用程序也是如此,还是我应该取消注释下面的锁定语句。
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);
}));
//}
}
}