Reputation: 4303
I am learning Threads. I am using thread to process an array of integers and strings.
Example :
class Program
{
static void Main()
{
ArrayProcess pr=new ArrayProcess();
ThreadStart callback1 = new ThreadStart(pr.PrintNumbers);
ThreadStart callback2 = new ThreadStart(pr.PrintStrings);
callback1 += callback2;
Thread secondaryThread = new Thread(callback1);
secondaryThread.Name = "worker1";
secondaryThread.Start();
Console.ReadKey(true);
}
}
class ArrayProcess
{
public void PrintNumbers()
{
int[] a = new int[] { 10, 20, 30, 40, 50 };
foreach (int i in a)
{
Console.WriteLine(i);
Thread.Sleep(1000);
Console.WriteLine("Printing Numbers");
}
}
public void PrintStrings()
{
string[] str = new string[] { "one", "two", "three", "four", "five" };
foreach (string st in str)
{
Console.WriteLine(st);
Thread.Sleep(1000);
Console.WriteLine("Printing string");
}
}
}
According to the code the execution of arrays are synchronous (i.e) int array is processed first and then the string array.Now how can i redesign the code to achieve asynchronous execution
(i.e) 10,20,One,30,two,three,...
Upvotes: 0
Views: 141
Reputation: 150108
You are actually only creating one extra thread. Try this to get two, asynchronous threads:
ThreadStart callback1 = new ThreadStart(pr.PrintNumbers);
ThreadStart callback2 = new ThreadStart(pr.PrintStrings);
Thread t1 = new Thread(callback1);
Thread t2 = new Thread(callback2);
t1.Name = "worker1";
t1.Start();
t2.Name = "worker2";
t2.Start();
Once you have mastered the basics of threads, I suggest you look into BackgroundWorker as a much easier way to manage threading.
Upvotes: 3