I have some very simple code that's attempting to multi-thread an existing script.
On inspecting the treads window in visual Studio and calling Thread.CurrentThread.ManagedThreadId
it always reports back as the same thread as starting the process. When ending it reports back a different thread id.
The threads do seem to be performing the task asynchronously, but the logging and output from visual studio are making me think otherwise.
Please could someone clarify what is going on and if I've made a mistake in my approach?
namespace ResolveGoogleURLs
{
class Program
{
public static void Main(string[] args)
{
HomeController oHC = new HomeController();
}
}
}
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
namespace ResolveGoogleURLs
{
class HomeController
{
public static int MaxJobs = 5;
public static int RecordsPerJob = 1000;
public static List<Task> TaskList = new List<Task>(MaxJobs);
public HomeController()
{
CreateJobs();
MonitorTasks();
}
public void MonitorTasks()
{
while (1 == 1)
{
Task.WaitAny(TaskList.ToArray());
TaskList.RemoveAll(x => x.IsCompleted);
Console.WriteLine("Task complete! Launching new...");
CreateJobs();
}
}
public async Task CreateJob()
{
Console.WriteLine("Thread {0} - Start", Thread.CurrentThread.ManagedThreadId);
// read in results from sql
await Task.Delay(10000);
Console.WriteLine("Thread {0} - End", Thread.CurrentThread.ManagedThreadId);
}
public void CreateJobs()
{
while (TaskList.Count < MaxJobs)
{
TaskList.Add( CreateJob() );
}
}
}
}
Output:
> Thread 1 - Start
Thread 1 - Start
Thread 1 - Start
Thread 1 - Start
Thread 1 - Start
Thread 4 - End
Thread 5 - End
Thread 4 - End
Thread 6 - End
Thread 8 - End
Task complete! Launching new...
Thread 1 - Start
Thread 1 - Start
Thread 1 - Start
Thread 1 - Start
Thread 1 - Start
Thread 7 - End
Thread 6 - End
Thread 5 - End
Thread 4 - End
Thread 8 - End
Task complete! Launching new...
Thread 1 - Start
Thread 1 - Start
Thread 1 - Start
Task complete! Launching new...
Thread 1 - Start
Thread 1 - Start
Thread 10 - End
Thread 9 - End
Task complete! Launching new...
Thread 1 - Start
Thread 7 - End
Thread 4 - End
Thread 6 - End
Task complete! Launching new...
Thread 1 - Start
Thread 1 - Start
Task complete! Launching new...
Thread 1 - Start
Thread 1 - Start