❔ 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"; } } }
// 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
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 partDo not use thread sleep in your async code. You have Task.Wait
thanks. I have trouble crreating the tasks. so I'm searching for an example where the comment // begin task is.
IEnumerableExtensions.Batch(IEnumerable, Int32) Method (Microsoft.A...
Batches an enumerable into batches of the specified size.
so something like....
if I understand what you're asking for correctly
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.
that's basically the same thing
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.