Reputation: 3464
I want to create a thread with a Dispatcher and then, from another thread, use that dispatcher to queue work with different priorities. i.e.
var dispatcher = GetNewThreadDispatcher();
dispatcher.BeginInvoke(longRunningTask1, DispatcherPriority.Normal);
dispatcher.BeginInvoke(longRunningTask2, DispatcherPriority.Background);
dispatcher.BeginInvoke(longRunningTask3, DispatcherPriority.Normal);
In this case, the background thread would perform longRunningTask1
, then longRunningTask2
, longRunningTask3
. I'm having difficulty creating a clean GetNewThreadDispatcher()
, any help?
Upvotes: 3
Views: 1038
Reputation: 3261
You can try to create new background thread ( http://msdn.microsoft.com/en-us/library/7a2f3ay4(v=vs.90).aspx) and get Dispatcher
for it:
Dispatcher dispatcher = Dispatcher.FromThread(workerThread);
Some edits:
You need to execute
Dispatcher dispatcher=Dispatcher.CurrentDispatcher
or Dispatcher.Run
inside OnThreadStart
. But interesting thing: after execute
workerThread.Start();
Dispatcher dispatcher = Dispatcher.FromThread(workerThread);
dispatcher
is null
but after execute
workerThread.Start();
Console.WriteLine("main thread: Starting worker thread...");
Dispatcher dispatcher = Dispatcher.FromThread(workerThread);
dispatcher
is filling
added:
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");
}
}
this code working in my test wpf app but i am not expert in multithreading. May be someone will correct me or add some info to this reply.
Upvotes: 2