Home > Software design >  My task is blocked with the function Task.WhenAll(allTasks) after doing some tasks
My task is blocked with the function Task.WhenAll(allTasks) after doing some tasks

Time:07-27

Is there an option to stop tasks if they exceed a certain time?

CodePudding user response:

if you want to process the files asynchronously then i would suggest using a channel as a file queue something like

var fileQueue = Channel.CreateUnbounded<string>();

async Task write(List<string> list)
{
    foreach (var item in list)
    {
        await fileQueue.Writer.WriteAsync(item);
    }
    fileQueue.Writer.TryComplete()
}
async Task read()
{
    while(await fileQueue.Reader.WaitToReadAsync())
    {
        var filename = await fileQueue.Reader.ReadAsync();
        await ProcessFile(filename);
    }

}

var writer = write(list);
var reader = read();

await Task.WaitAll(writer, reader);

EDIT: you have edited your question with a second question

you can abort a running task but this is generally a bad idea as you have no guarantee that the code it in a fit state to stop what it is doing

the preferred approach is to pass in a cancellation token then the running task periodically checks the token and if it indicates that a cancel is requested it gracefully cancels

  •  Tags:  
  • c#
  • Related