C# how to work with list of task
Hello guys
I'm trying to work with a list of tasks but the problem is I can't get a list of run tasks
how can I get the list of run tasks without list<>?
.NET CLI
C#
-
AgaveJoe 28,291 Reputation points
2021-10-02T15:59:55.287+00:00 Can you clarify the question or provide sample code that illustrates the problem you are trying to solve?
-
Dani_hnr 1 Reputation point
2021-10-02T16:29:18.6+00:00 for example, i have a list that name is ids
and have 10 field
and I want to turn of id 5
how can I do that
my code :
class Program
{
static void Main(string[] args)
{
foreach (var id in ids)
{
RunAsync(id);
}
}
public async Task RunAsync(int id)
{
while (true)
{
Console.WriteLine($"run {id}");
}
}
} -
P a u l 10,731 Reputation points
2021-10-02T16:42:20.03+00:00 The first issue that I can spot is that
RunAsync
is actually synchronous (i.e. it uses neither theawait
keyword, or return aTask
.) If you want your loop to be run inside a task you can useTask.Run
to wrap your loop. Once you're returning aTask
to theMain
method, it will be able toawait
it.The second issue is that your
Main
method doesn'tawait
the response, so the program will exit potentially before your loops even begin. YourRunAsync
also needs to be static, as it's being called by yourMain
method, which is static and static methods can't call instance methods.If you make
RunAsync
static though you'll now have a new issue, which is that your firstid
will block the loop from iterating, so you'll just see a stream of your first ids being printed down the page. The way around this (now thatRunAsync
returns aTask
) is to add all the response tasks to a collection, then useTask.WhenAll
on the collection, which will keep all of your tasks running until completion (which is your case is indefinitely.)Here's something to get you started:
class Program { static async Task Main(string[] args) { int[] ids = new[] { 1, 2, 3 }; List<Task> tasks = new List<Task>(); foreach (var id in ids) { tasks.Add(RunAsync(id)); } await Task.WhenAll(tasks); } public static Task RunAsync(int id) { return Task.Run(() => { while (true) { Console.WriteLine($"run {id}"); } }); } }
-
Dani_hnr 1 Reputation point
2021-10-02T17:23:32.07+00:00 you didn't get what I mean let me give another example :`
namespace Bot { class Program { static void Main(string[] args) { using (var ctx = new LuckyDuckDbContext()) { foreach (var bot in ctx.Bots.ToList()) { MainAsync(bot.Token); } } } public static async Task MainAsync(string token) { var discord = new DiscordClient(new DiscordConfiguration() { Token = token, TokenType = TokenType.Bot, Intents = DiscordIntents.AllUnprivileged }); await discord.ConnectAsync(); await Task.Delay(-1); } } }
now if I want stop one of them
what should I do -
P a u l 10,731 Reputation points
2021-10-02T18:28:51.733+00:00 You'll want to create a
CancellationTokenSource
, which you'll use to both stop yourTask.Delay(-1)
and also callDisconnectAsync
on your discord client. You'll want to create this inside ofMain
and pass it into yourMainAsync
.Here's an example of how you'd create/use a token:
https://video2.skills-academy.com/en-us/dotnet/standard/parallel-programming/task-cancellationTask.Delay
has a constructor that accepts aCancellationToken
, which is where you'll want to pass yourCancellationTokenSource.Token
to:
https://video2.skills-academy.com/en-us/dotnet/api/system.threading.tasks.task.delay?view=net-5.0#System_Threading_Tasks_Task_Delay_System_Int32_System_Threading_CancellationToken_Inside your
MainAsync
method you'll want to register a callback on yourCancellationToken
by callingRegister
on it, which you'll pass an action to, and that is where you'll want to calldiscord.DisconnectAsync()
:
https://video2.skills-academy.com/en-us/dotnet/api/system.threading.cancellationtoken?view=net-5.0#methodsOnce this is setup you should be able to just call
.Cancel()
on yourCancellationTokenSource
and that'll stop both yourTask.Delay
and disconnect your Discord client.
Sign in to comment