测试kadh
静态同步任务运行程序(
{
vartaskqueue=newconcurrentqueuecustomtask (;
varcts=newcancellationtokensource (;
//生成任务并将其添加到并发队列
var taskSource=Task.Run (()=taskproducer ) taskqueue );
//同时启动四个任务处理队列中的任务
Task[] processors=new Task[4];
for(intI=1; i=4; I )
{
string processId=i.ToString (;
处理程序[ I-1 ]=task.run (
() ()任务处理器(taskqueue,' Processor ' processId,cts.Token ) ) ) ) ) ) ) )
);
}
等待任务源;
//向任务发送取消信号
cts.cancel after (timespan.from seconds (2) );
await task.when all (处理器;
}
生成任务
静态同步任务生产程序(concurrentqueuecustomtaskqueue ) )。
{
for(intI=0; i 20; I )
{
awaittask.Delay(50;
var work item=newcustomtask { id=I };
queue.enqueue (工作项目;
}
}
执行任务
静态同步任务处理程序(concurrentqueuecustomtaskqueue、string name、CancellationToken token ) )。
{
自定义任务工作项目;
bool dequeueSuccesful=false;
await美丽的香菇(;
德奥
{
dequeue succesful=queue.try dequeue (outwork item );
需求成功(if ) )。
{
}
await美丽的香菇(;
}
while (! token.IsCancellationRequested;
}
静态任务的美丽香菇() ) ) )。
{
int delay=new random (datetime.now.millisecond ).next ) 1500;
返回任务. delay (delay;
}
类自定义任务
{
公共int id { get; set; }
}
框中,选择“默认值”
staticvoidmain (字符串[ ] args ) )。
{
任务t=run program (;
t.Wait (;
控制台. read key (;
}