你可以嘗試創建新的後臺線程(http://msdn.microsoft.com/en-us/library/7a2f3ay4(v=vs.90).aspx),並得到Dispatcher
它:
Dispatcher dispatcher = Dispatcher.FromThread(workerThread);
部分編輯: 您需要執行內部OnThreadStart
Dispatcher dispatcher=Dispatcher.CurrentDispatcher
或Dispatcher.Run
。但有趣的事:後執行
workerThread.Start();
Dispatcher dispatcher = Dispatcher.FromThread(workerThread);
dispatcher
是null
但執行
workerThread.Start();
Console.WriteLine("main thread: Starting worker thread...");
Dispatcher dispatcher = Dispatcher.FromThread(workerThread);
dispatcher
充盈
添加後:
static void OnThreadStart()
{
Dispatcher.Run();
}
private Dispatcher GetNewThreadDispatcher()
{
Thread workerThread=null;
try
{
workerThread = new Thread(OnThreadStart);
workerThread.IsBackground = true;
workerThread.Start();
int waitingCiclesCount = 100;
int cicleIndex = 0;
int sleepTimeInMiliseconds = 100;
Dispatcher dispatcher = null;
while (cicleIndex < waitingCiclesCount)
{
dispatcher = Dispatcher.FromThread(workerThread);
if (dispatcher!=null)
break;
Thread.Sleep(sleepTimeInMiliseconds);
cicleIndex = cicleIndex + 1;
}
if (dispatcher==null)
{
workerThread.Abort();
return null;
}
Console.WriteLine(String.Format("thread with id={0} started", workerThread.ManagedThreadId));
return dispatcher;
}
catch (Exception)
{
if (workerThread!=null)
workerThread.Abort();
return null;
}
}
public MainWindow()
{
InitializeComponent();
TestWorker worker=new TestWorker();
Dispatcher dispatcher1 = GetNewThreadDispatcher();
if(dispatcher1!=null)
dispatcher1.BeginInvoke(new TestDelegate(worker.DoWork1), DispatcherPriority.Normal);
else
{
MessageBox.Show("Cant create dispatcher1");
}
Dispatcher dispatcher2 = GetNewThreadDispatcher();
if (dispatcher2!=null)
dispatcher2.BeginInvoke(new TestDelegate(worker.DoWork2), DispatcherPriority.Normal);
else
{
MessageBox.Show("Cant create dispatcher2");
}
}
這個代碼在我的測試WPF應用程序工作但我不是多線程專家。可能有人會糾正我或在此回覆中添加一些信息。
是否有任何理由不想使用應用程序分派器? –
新線程用於後臺工作,與UI或渲染無關,只是使用Dispatcher對象來管理線程的工作。 –
BeginInvoke將啓動一個新的線程: 'Application.Current.Dispatcher.BeginInvoke(DispatcherPriority.Background,(Action)delegate {MyMethod();});' –