简体   繁体   中英

How to cancel task but let her to finish the chunk?

I have a program (.NET Core C#) that delete data from DB, for each account - deletes all the data related to the account. I want to add an option to stop the program but finish the deletion for the person the program is on and then stop and exit. I want to do something like this, when I press any key then the program will finish printing 10 entries and then stop and exit. this is for example :

public static void Main(string[] args)
{
    // ???
    
}


static void Console_CancelKeyPress(object sender, ConsoleCancelEventArgs e)
{
    Console.WriteLine("Shutting down...");
    // Cleanup here
}

private static async Task MyTask(CancellationToken cancellationToken)
{
    Print(cancellationToken);
}

public static void Print(CancellationToken cancellationToken)
{
    while (cancellationToken.IsCancellationRequested!)
    {
        for (int i = 1; i < 10; i++)
        {
            Console.WriteLine(i);
        }
    }
}

I would like to any idea you have,
Thanks!

Just don't pass cancellationToken to dbContext. Check cancellationToken manually when ever you can stop your program.

private static async Task DeleteAllAccounts(CancellationToken cancellationToken)
{
    var accounts = await GetAccountsAsync(cancellationToken);
    foreach (var account in accounts)
    {
        await DeleteAccountAsync(account, CancellationToken.None);
        if (cancellationToken.IsCancellationRequested)
            break;
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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