具有异步顺序任务C#的TaskScheduler [英] TaskScheduler with async sequential Tasks C#
问题描述
我正在异步执行一些.py脚本。一个脚本执行大约需要30秒。可能会在两到三秒的时间范围内选择两个或更多脚本。目标是拥有一个计划程序,该计划程序收集所有任务并一个接一个地执行它们。应该包括一个FIFO功能。
我已经尝试了以下代码,只是为了尝试queuedTaskScheduler的功能,但即使这样也不起作用。
I am executing some .py scripts async. One Script takes about 30 seconds to be executed. It could happen that two or even more Scripts are being selected in a timespan of two or three seconds. The Goal is to have a Scheduler which collects all the tasks and executes them one after the other. A FIFO functionality should be included. I 've tried the following Code just to try the functionality of the queuedTaskScheduler, but even that doesn't work.
QueuedTaskScheduler queueScheduler;
private TaskScheduler ts_priority1;
int pos = 0;
public Form1()
{
InitializeComponent();
queueScheduler = new QueuedTaskScheduler(targetScheduler: TaskScheduler.Default, maxConcurrencyLevel: 1);
ts_priority1 = queueScheduler.ActivateNewQueue(1);
}
private void button3_Click(object sender, EventArgs e)
{
QueueValue(pos, ts_priority1);
pos++;
}
private void button4_Click(object sender, EventArgs e)
{
changeString(pos);
pos++;
}
private void changeString (int position)
{
var bea = "This is Thread " + position + " starting";
MethodInvoker Labelupdate = delegate
{
label2.Text = bea;
};
Invoke(Labelupdate);
Thread.Sleep(3000);
bea = "Thread " + position + " is ending";
MethodInvoker Labelupdate1 = delegate
{
label2.Text = bea;
};
Invoke(Labelupdate1);
Thread.Sleep(1000);
}
private void updateLabel (string Lab)
{
MethodInvoker Labelupdate = delegate
{
label2.Text = Lab;
};
Invoke(Labelupdate);
}
private Task QueueTask(Func<Task> f, TaskScheduler ts)
{
return Task.Factory.StartNew(f, CancellationToken.None, TaskCreationOptions.HideScheduler | TaskCreationOptions.DenyChildAttach, ts);
}
private Task QueueValue(int position, TaskScheduler ts)
{
return QueueTask(async () =>
{
label2.Text = "This is Thread " + position + " starting";
Thread.Sleep(3000);
label2.Text = "Thread " + position + " is ending";
Thread.Sleep(1000);
}, ts);
}
推荐答案
我解决了。只需要一个信号量。与此 Thread
这是代码:
I solved it. There is only need of a Semaphore. It is the same way as in this Thread Here is the Code:
private static SemaphoreSlim semaphore = new SemaphoreSlim(1);
private Task QueueValue(int position, TaskScheduler ts)
{
return QueueTask(async () =>
{
await semaphore.WaitAsync();
try
{
var at = "This is Thread " + position + " starting";
updateLabel(at);
await Task.Delay(3000);
at = "Thread " + position + " is ending";
updateLabel(at);
await Task.Delay(1000);
}
finally
{
semaphore.Release();
}
}, ts);
}
非常感谢!
这篇关于具有异步顺序任务C#的TaskScheduler的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!