I can't seem to get thread.Join() to work for this example. I'm new to multithreading and C# so I am kind of unsure how to apply the online examples into my own coding. Here's an example of my coding:
using System;
using System.Threading;
public class Example
{
static Thread thread1, thread2, thread3, thread4;
public static void Main()
{
Console.WriteLine("Starting thread1");
thread1 = new Thread(ThreadProc);
thread1.Name = "Thread1";
thread1.Start();
Console.WriteLine("Starting thread2");
thread2 = new Thread(ThreadProc2);
thread2.Name = "Thread2";
thread2.Start();
Console.WriteLine("Starting thread3");
thread3 = new Thread(ThreadProc3);
thread3.Name = "Thread3";
thread3.Start();
Console.WriteLine("Starting thread4");
thread4 = new Thread(ThreadProc4);
thread4.Name = "Thread4";
thread4.Start();
}
private static void ThreadProc()
{
//do work and creates textfile1 to store results
sharedMethod();
//do work until thread finishes
}
private static void ThreadProc2()
{
//do work and creates textfile2 to store results
sharedMethod();
//do work until thread finishes
}
private static void ThreadProc3()
{
//do work and creates textfile3 to store results
sharedMethod();
//do work until thread finishes
}
private static void ThreadProc4()
{
//do work and creates textfile4 to store results
sharedMethod();
//do work until thread finishes
}
private static void sharedMethod()
{
//wait the current thread to finish before allowing next thread to use
//reads and prints the correct textfile for each thread to my printer
}
}
I have 4 threads here that are using ThreadProc as their main functions. These main functions will then call a shared function that will print my results with my printer here. The problem appears that the printer is still busy receiving data/printing results from the previous thread but the new current thread comes in pre-maturely and causes the printer to not print the next results. Any help?
It sounds like you just want a lock, using a static field for an object whose monitor you lock on:
private static readonly object lockForSharedMethod = new object();
...
private static void SharedMethod()
{
lock(lockForSharedMethod)
{
// Code in here will only execute in a single thread
}
}
See more on this question at Stackoverflow