That is the question!
When is multi-threading an application a must, and what to consider in multi-threading in general?
It would be greatly appreciated if an example is posted along with the explanation.
Thanks.
PS. I tried checking all the possible questions before posting, if this question is simply another duplicate, please close it.
For example we can understand multi threading by the process of billing at billing counter of a shop or a MALL. so only one counter is a single threaded process and multi counters is a multi threaded process.so in multi threading the whole process of billing is divided into many sub processes by many billing counters (multiple threads) aim at doing the billing job.
So for implementation of threads we have following example:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
namespace ThredsRND
{
public abstract class TaskRequest
{
}
public abstract class TaskManager<T> where T : TaskRequest
{
protected Queue<T> Requests = new Queue<T>();
private int NumberOfThreads { get; set; }
public void Run(int _numberOfThreads)
{
NumberOfThreads = _numberOfThreads;
CreateTasks();
List<Thread> threads = new List<Thread>();
if (NumberOfThreads <= 0)
NumberOfThreads = 1;
for (int i = 0; i < NumberOfThreads; i++)
{
Thread th = new Thread(_ExecuteThread);
th.Start();
threads.Add(th);
}
threads.ForEach(x => x.Join());
}
private object _key = new object();
private void _ExecuteThread()
{
while (true)
{
T request = null;
lock (_key)
{
if (Requests.Count > 0)
request = Requests.Dequeue();
}
if (request != null)
{
Console.WriteLine("THREAD:" + Thread.CurrentThread.ManagedThreadId);
ExecuteTask(request);
}
else return;
}
}
public abstract void CreateTasks();
public abstract void ExecuteTask(T request);
}
}
now this taskManager class will have to be inherited and its abstract functions need to be defined.
for example:
class SimpleReportRequest:TaskRequest
{
public int Start { get; set; }
public int End { get; set; }
}
class SimpleReportCreator : TaskManager<SimpleReportRequest>
{
public override void CreateTasks()
{
for (int i = 1; i <= 100; i++)
{
SimpleReportRequest req = new SimpleReportRequest();
req.Start = i;
req.End = i+1;
Requests.Enqueue(req);
}
}
public override void ExecuteTask(SimpleReportRequest request)
{//what each process of this type should doo..
}
The Main Program;
static void Main(string[] args)
{
SimpleReportCreator creator = new SimpleReportCreator();
DateTime start = DateTime.Now;
Console.WriteLine("started at: "+ start);
creator.Run(100);
DateTime end = DateTime.Now;
Console.WriteLine("Total Time taken with threads: " +(end-start));
Console.WriteLine("ALL END");
Console.ReadLine();
return;}
HOPE THIS POST IS VERY MUCH USEFUL
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With