I'm creating a list in C# synchronously but it's slow. There's about 50 items in the list and it can take up to 20 seconds to add each item. The method to add the item can be asynchronous so I'm wondering if I can add all of them using async/await somehow.
Here's a simple example of adding 2 items to a list synchronously. How would I do it asynchronously? Is it even possible? Would you get "collisions" if you tried to add to the list at the same time?
using System.Threading;
using System.Collections.Generic;
class Program
{
static void Main(string[] args)
{
List<int> lst = null;
lst=GetList();
}
static List<int> GetList()
{
List<int> lst = new List<int>();
//add to list
lst.Add(Task1());
lst.Add(Task2());
//return list
return lst;
}
static int Task1()
{
Thread.Sleep(10000);
return 1;
}
static int Task2()
{
Thread.Sleep(10000);
return 2;
}
}
Compufreak's answer was just what I was looking for. I have a related question although I'm not sure if this is how I'm supposed to ask it. I modified Compufreak's code slightly to a way that makes more sense to me and I'm wondering if there is any actual difference in the way the code works. I took the async/await out of Task1 and Task2 and just created a Task and passed Task1 and Task2 in as parameters.
using System;
using System.Threading;
using System.Threading.Tasks;
using System.Collections.Generic;
using System.Linq;
class Program
{
static async Task Main(string[] args)
{
List<int> lst = null;
DateTime StartTime = DateTime.Now;
lst = await GetList();
DateTime EndTime = DateTime.Now;
Console.WriteLine("ran tasks in " + (EndTime - StartTime).TotalSeconds + " seconds");
Console.ReadLine();
}
static async Task<List<int>> GetList()
{
var tasks = new List<Task<int>>();
//add task to list of tasks
tasks.Add(new Task<int>(Task1));
tasks.Add(new Task<int>(Task2));
//start tasks
foreach(Task<int> t in tasks)
{
t.Start();
}
//await results
int[] results = await Task.WhenAll(tasks);
//return list
return results.ToList();
}
static int Task1()
{
Thread.Sleep(10000);
return 1;
}
static int Task2()
{
Thread.Sleep(10000);
return 2;
}
}