I made a program that does a long task. In this task I need to perform a "await" call, but I don't really know how to make this multithreaded. This is my code:
ApplicationDbContext db = new ApplicationDbContext();
foreach (var apiaccount in db.APIAccounts.ToArray())
{
var max = db.Chats.Where(a => a.apiaccountid == apiaccount.id).Max(a => a.ended);
var start = max != null ? max.Value : new DateTime(2014, 10, 1, 1, 0, 0);
if (start.Hour == 0)
{
start = start.AddDays(-1);
}
var mod = new ImportAPIModel()
{
email = apiaccount.Email,
token = apiaccount.Token,
startdate = start,
stopdate = null,
importid = importid,
apiaccountid = apiaccount.id
};
await ImportAPI(mod);
}
//async Task ImportAPI(object obj)
There are only a few accounts, so I want the code to start next to eachother. So I change the code to:
ApplicationDbContext db = new ApplicationDbContext();
List<Thread> threads = new List<Thread>();
foreach (var apiaccount in db.APIAccounts.ToArray())
{
var max = db.Chats.Where(a => a.apiaccountid == apiaccount.id).Max(a => a.ended);
var start = max != null ? max.Value : new DateTime(2014, 10, 1, 1, 0, 0);
if (start.Hour == 0)
{
start = start.AddDays(-1);
}
var mod = new ImportAPIModel()
{
email = apiaccount.Email,
token = apiaccount.Token,
startdate = start,
stopdate = null,
importid = importid,
apiaccountid = apiaccount.id
};
//await ImportAPI(mod);
Thread thread = new Thread(new ParameterizedThreadStart(ImportAPI));
thread.Start(mod);
threads.Add(thread);
}
foreach (var thread in threads) thread.Join();
//async Task ImportAPI(object obj)
But this doesn't compile as the thread cannot use the Task type. If I then change it to void it does run, but doesnt wait on the .Join() command.
It seems to me like this should be really easy with async programming, I just don't get how. I've tried to find some information on this on google, but with no result. So this is why I'm asking. I hope I won't be tagged as duplicate, but if so, I will be helped anyways :) So thank you all in advance! Stackoverflow is the best.