Monica

Monica

  • NA
  • 16
  • 0

Multithreading: how to create different threads (which all do the same job) but with different parameters ??

Feb 25 2009 10:09 AM

 

Hi there,

Basically I am a bit confusing about multithreading...I have created this class ThreadJob that holds the work that every thread has to do, which basically is copying files from one directory to another. I try to create different threads as follows :

class Program

{

static void Main(string[] args)

{

ThreadJob tj = new ThreadJob(1, "d:\\Copy\\one", "d:\\Copy\one 1");

new Thread(new ThreadStart(tj.Copy)).Start();

ThreadJob tj2 = new ThreadJob(2, "d:\\Copy\\two", "d:\\Copy\\two 1");

new Thread(new ThreadStart(tj2.Copy)).Start();

Console.ReadLine();

}

}

 

class ThreadJob

{

int iJobId;

Boolean bDone;

string szFromPath;

string[] szToPath;

int iThreadId;

int iId = 1;

string szError = "";

public ThreadJob(int jobId, string fromPath, string[] toPath)

{

iJobId = jobId;

szFromPath = fromPath;

szToPath = toPath;

iThreadId = iId;

bDone = false;

iId++;

}

public int ThreadId

{

get { return (iThreadId); }

}

public Boolean Done

{

get { return (bDone); }

}

public String Error

{

get { return (szError); }

}

public void Start()

{

//Do the copying

try

{

//Check if the scan directory exists

DirectoryInfo di = new DirectoryInfo(szFromPath);

if (di.Exists)

{

FileInfo[] files = di.GetFiles();

foreach (FileInfo fi in files)

{

bool bError = false;

foreach (string dup in szToPath)

{

//Check that the directory exists

DirectoryInfo dir = new DirectoryInfo(dup);

if (dir.Exists)

{

//Try copying the files

try

{

fi.CopyTo(dup);

}

catch (Exception ex)

{

szError += "Error copying file \"" + fi.Name + "\" to directory \"" + dup + "\".Reason: " + ex.ToString() + Environment.NewLine;

bError = true;

}

}

else

{

szError += "Copying directory \"" + dup + "\" does not exists" + Environment.NewLine;

break;

}

}

if (bError == false)

{

//There were no errors copying file to all dups. Delete it

fi.Delete();

}

else

{

szError += "Finished copying files from \"" + szFromPath + "\". There were errors copying the files from this directory." + Environment.NewLine;

}

}

}

else

{

szError += "Scan directory \"" + szFromPath + "\" does not exists" + Environment.NewLine;

}

}

catch (Exception ex)

{

szError += "Error copying files from \"" + szFromPath + "\". Reason: " + ex.ToString() + Environment.NewLine;

}

finally

{

bDone = true;

}

}

}

 

My question is ...how can i create several threads which will be doing the same thing, the only difference will be that the arguments for one thread will be diferrent to the other.

Any help will be highly appreciate.

Cheers

PS: How can i have threads accessing the same method!? Am I suppose to create as many methods as threads - this will be unlikely, right? :( ...


Answers (2)