Click to See Complete Forum and Search --> : Threads


JynxRD
May 10th, 2009, 04:07 PM
I'm learning threads currently and I'm a bit stumped. Hopefully someone can help me along here.

Here are my instructions from my book exactly as they are written

======
Write a C# application that has five threads running at the same time. Each thread outputs to the console the following five strings ten times each ("AAA", "BBB", "CCC", "DDD", "EEE"). You should only need a single method that actually does the work, you will create multiple threads using this single method.
======


This is what I put together while trying to learn threads but I'm not sure how to do what they are asking.


using System;
using System.Text;
using System.Threading;

class Test
{
static void MyThreadMethod()
{
Console.WriteLine("AAA, BBB, CCC, DDD, EEE.");
Console.ReadLine();
}

static void Main()
{
Thread threadObj = new Thread(new ThreadStart(MyThreadMethod));
threadObj.Start();

}
}

dglienna
May 10th, 2009, 08:11 PM
There's a link in my signature to download 101 Samples for VB/C# that should help you. Barring that, you can find it on MSDN yourself

novice_andrei
May 10th, 2009, 08:38 PM
Wow interesting exercise; I'm trying to learn too.

About the requirements, how can it be done in a single method, when the very constructor of the thread requires a threadstart object that takes another method as parameter?

Anyways, I tried the exercise too, here's what I came up with...


private static void GenerateThreads()
{
int threadCount = 0;
while (threadCount < 5)
{
Thread t = new Thread(new ThreadStart(ShowText));
t.Name = threadCount.ToString();
t.Start();

threadCount ++;
}
}

public static void ShowText()
{
switch (Thread.CurrentThread.Name)
{
case "0":
for (int i = 0; i < 10; i++)
Console.WriteLine("AAA");
break;
case "1":
for (int i = 0; i < 10; i++)
Console.WriteLine("BBB");
break;
//etc...
}
}


of course it does not work :D for some reason, it never enters the ShowText method.

JynxRD
May 10th, 2009, 08:43 PM
I think I figured it out.


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;

namespace ConsoleApplication2
{
class Test
{
static void MyThreadMethod(object arg)
{
for (int i = 0; i < 10; i++)
{
Console.WriteLine((string)arg);
}
}

static void Main()
{
Thread a = new Thread(new ParameterizedThreadStart(MyThreadMethod));
a.Start("AAA");
Thread b = new Thread(new ParameterizedThreadStart(MyThreadMethod));
b.Start("BBB");
Thread c = new Thread(new ParameterizedThreadStart(MyThreadMethod));
c.Start("CCC");
Thread d = new Thread(new ParameterizedThreadStart(MyThreadMethod));
d.Start("DDD");
Thread e = new Thread(new ParameterizedThreadStart(MyThreadMethod));
e.Start("EEE");
Console.ReadLine();
}
}
}

novice_andrei
May 10th, 2009, 08:56 PM
I should've seen that :) i could not pass a method with parameters to the ThreadStart object so the solution was ParameterizedThreadStart

good thinking :)