简体   繁体   English

如何在c#中运行多个任务并在完成这些任务时获取事件?

[英]How to run multiple tasks in c# and get an event on complete of these tasks?

I am re-running a Task when its completed. 完成后我正在重新运行Task Below is the function I call in the Application_Start of my application. 下面是我在我的应用程序的Application_Start中调用的函数。

private void Run()
{
    Task t = new Task(() => new XyzServices().ProcessXyz());
    t.Start();
    t.ContinueWith((x) =>
    {
        Thread.Sleep(ConfigReader.CronReRunTimeInSeconds);
        Run();
    });
}

I want to run multiple tasks, number which will be read from web.config app setttings. 我想运行多个任务,编号将从web.config app setttings中读取。

I am trying something like this, 我正在尝试这样的事情,

private void Run()
{
    List<Task> tasks = new List<Task>();
    for (int i = 0; i < ConfigReader.ThreadCount - 1; i++)
    {
        tasks.Add(Task.Run(() => new XyzServices().ProcessXyz()));
    }

    Task.WhenAll(tasks);

    Run();
}

Whats the correct way to do this ? 这是正确的方法吗?

I believe you are looking for: 我相信你在寻找:

Task.WaitAll(tasks.ToArray());

https://msdn.microsoft.com/en-us/library/dd270695(v=vs.110).aspx https://msdn.microsoft.com/en-us/library/dd270695(v=vs.110).aspx

if you want to run the tasks one after the other, 如果你想一个接一个地运行任务,

await Task.Run(() => new XyzServices().ProcessXyz());
await Task.Delay(ConfigReader.CronReRunTimeInSeconds * 1000);

if you want to run them concurrently, as the task scheduler permits, 如果你想同时运行它们,就像任务调度程序允许的那样,

await Task.WhenAll(new[]
    {
        Task.Run(() => new XyzServices().ProcessXyz()),
        Task.Run(() => new XyzServices().ProcessXyz())
    });

So, your method should be something like, 所以,你的方法应该是这样的,

private async Task Run()
{
    var tasks =
        Enumerable.Range(0, ConfigReader.ThreadCount)
        .Select(i => Task.Run(() => new XyzServices().ProcessXyz()));

    await Task.WhenAll(tasks); 
}

If you want to wait all tasks to finish and then restart them, Marks's answer is correct. 如果您想等待所有任务完成然后重新启动它们,Marks的答案是正确的。

But if you want ThreadCount tasks to be running at any time (start a new task as soon as any one of them ends), then 但是如果你想让ThreadCount任务随时运行(一旦任何一个任务结束就开始一个新任务),那么

void Run()
{
    SemaphoreSlim sem = new SemaphoreSlim(ConfigReader.ThreadCount);

    Task.Run(() =>
    {
        while (true)
        {
            sem.Wait();
            Task.Run(() => { /*Your work*/  })
                .ContinueWith((t) => { sem.Release(); });
        }
    });
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM