gpt4 book ai didi

c# - 设置调度程序以优先队列工作

转载 作者:行者123 更新时间:2023-11-30 17:08:27 38 4
gpt4 key购买 nike

我想创建一个带有 Dispatcher 的线程,然后在另一个线程中使用该 Dispatcher 对具有不同优先级的工作进行排队。即

var dispatcher = GetNewThreadDispatcher();
dispatcher.BeginInvoke(longRunningTask1, DispatcherPriority.Normal);
dispatcher.BeginInvoke(longRunningTask2, DispatcherPriority.Background);
dispatcher.BeginInvoke(longRunningTask3, DispatcherPriority.Normal);

在这种情况下,后台线程将执行 longRunningTask1,然后是 longRunningTask2longRunningTask3。我在创建干净的 GetNewThreadDispatcher() 时遇到困难,有什么帮助吗?

最佳答案

您可以尝试创建新的后台线程(http://msdn.microsoft.com/en-us/library/7a2f3ay4(v=vs.90).aspx)并获取Dispatcher为此:

Dispatcher dispatcher = Dispatcher.FromThread(workerThread);

一些编辑:你需要执行
Dispatcher dispatcher=Dispatcher.CurrentDispatcherDispatcher.Run里面OnThreadStart .但有趣的是:执行后

workerThread.Start();
Dispatcher dispatcher = Dispatcher.FromThread(workerThread);

dispatchernull但是在执行之后

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 应用程序中工作,但我不是多线程方面的专家。可能有人会纠正我或在此回复中添加一些信息。

关于c# - 设置调度程序以优先队列工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13755056/

38 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com