C
C#17mo ago
Bailey

❔ Searching for good multiTask Example in List<task>

Hello, I'm seeking a good example of a multitask async I hope to clearify my question with the code. I'm trying to start multiple tasks which are defined in a list. Every time I try, I get stuck. I also want to be able to limit the amount of tasks. I hope someone has a simple example. Best Regards Code: namespace ConsoleApp1 { internal class Program { static void Main(string[] args) { // create objects to start a scoped task List<DiffentClass> diffentClasses = new List<DiffentClass>(); for (int i = 0; i < 10; i++) diffentClasses.Add(new DiffentClass()); foreach (var diffentClass in diffentClasses) { // begin task }
// Wait to finisch and merge ... } } } the task should be directed to: namespace OtherProjectApp { public class DiffentClass { public async Task<string> PlaceHolder(string LotsOfDate, int taskNumber) { for (int i = 0; i < 10000; i++) { Thread.Sleep(1000); await Console.Out.WriteLineAsync($"placeholder {taskNumber.ToString()}" ); } return "ready"; } } }
8 Replies
Omnissiah
Omnissiah17mo ago
in an async world you usually have Task.WhenAll to wait for tasks so i would say just use that instead of foreach (var diffentClass in diffentClasses) and the wait part
Denis
Denis17mo ago
Do not use thread sleep in your async code. You have Task.Wait
Bailey
BaileyOP17mo ago
thanks. I have trouble crreating the tasks. so I'm searching for an example where the comment // begin task is.
Mayor McCheese
Mayor McCheese17mo ago
so something like....
List<Thing> items = GetListOfThings();
var batches = items.Batch(8);

foreach(var batch in batches)
{
var tasks = batch.Select(DoSomthingToGetATaskFromAThing);
await Task.WhenAll(tasks);
}
List<Thing> items = GetListOfThings();
var batches = items.Batch(8);

foreach(var batch in batches)
{
var tasks = batch.Select(DoSomthingToGetATaskFromAThing);
await Task.WhenAll(tasks);
}
if I understand what you're asking for correctly
Bailey
BaileyOP17mo ago
thank you, I also foundd something on the internet namely: https://learn.microsoft.com/en-us/dotnet/standard/parallel-programming/task-based-asynchronous-programming Task[] taskArray = new Task[10]; for (int i = 0; i < taskArray.Length; i++) { taskArray[i] = Task.Factory.StartNew((Object obj) => { CustomData data = obj as CustomData; if (data == null) return; data.ThreadNum = Thread.CurrentThread.ManagedThreadId; }, new CustomData() { Name = i, CreationTime = DateTime.Now.Ticks }); } Task.WaitAll(taskArray); I will test them both.
Task-based asynchronous programming - .NET
In this article, learn about task-based asynchronous programming through the Task Parallel Library (TPL) in .NET.
Mayor McCheese
Mayor McCheese17mo ago
that's basically the same thing
Accord
Accord17mo ago
Was this issue resolved? If so, run /close - otherwise I will mark this as stale and this post will be archived until there is new activity.
Want results from more Discord servers?
Add your server