Skip to content

Instantly share code, notes, and snippets.

@ukcoderj
Last active April 3, 2023 11:18
Show Gist options
  • Save ukcoderj/55aca3f01c9d8d2669ecb051b47abf96 to your computer and use it in GitHub Desktop.
Save ukcoderj/55aca3f01c9d8d2669ecb051b47abf96 to your computer and use it in GitHub Desktop.
Run a List of Task And Get Results
// See https://aka.ms/new-console-template for more information
using DoTaskAndGetResult;
Console.WriteLine("Hello, World!");
TestClass tc = new TestClass();
List<Task<TestData>> taskList = new List<Task<TestData>>();
for(int i = 0; i < 1000; i++)
{
taskList.Add(tc.FillData(i.ToString()));
}
var ans = Task.WhenAll(taskList).Result;
foreach(var row in ans)
{
// This will output a list of data. The input order will be sequential, but the processed times will vary (as they were dealt with in parallel)
Console.WriteLine(row.OutputString);
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DoTaskAndGetResult
{
public class TestClass
{
public async Task<TestData> FillData(string input)
{
await Task.Delay(10);
var i1 = input;
var now = DateTime.UtcNow.ToString("HH:mm:ss.ffff");
var output = $"{i1} processed at {now}";
var td = new TestData(i1, output);
return td;
//return Task.FromResult(td);
}
}
public class TestData
{
public TestData(){ }
public TestData(string input, string output)
{
InputString = input;
OutputString = output;
}
public string InputString { get; set; }
public string OutputString { get; set; }
}
}

This shows how to run a multi threaded process and wait for the results of all tasks.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment