让当前线程先使用该函数,然后再让其他线程调用它C#
我似乎无法使让当前线程先使用该函数,然后再让其他线程调用它C#,c#,multithreading,C#,Multithreading,我似乎无法使thread.Join()用于此示例。我不确定如何将在线示例应用到我自己的代码中。下面是我的代码示例: using System; using System.Threading; public class Example { static Thread thread1, thread2, thread3, thread4; public static void Main() { Console.WriteLine("Starting thr
thread.Join()
用于此示例。我不确定如何将在线示例应用到我自己的代码中。下面是我的代码示例:
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
}
}
我这里有4个线程使用ThreadProc作为它们的主要函数。然后,这些主要函数将调用一个共享函数,该函数将在此处使用打印机打印结果。问题似乎是打印机仍在忙于从上一个线程接收数据/打印结果,但新的当前线程提前进入,导致打印机无法打印下一个结果。有什么帮助吗?如果您坚持使用
线程.Join来解决此问题,请按以下步骤执行:
Console.WriteLine("Starting thread1");
thread1 = new Thread(ThreadProc);
thread1.Name = "Thread1";
thread1.Start();
thread1.Join();
其他线程也是如此。尽管这样做违背了使用线程的目的
如果要防止多个线程同时输入sharedMethod
,请使用
我想向您介绍C#中的所有老式线程基础知识。听起来您只是想要一个锁,使用一个静态字段来锁定监视器上的对象:
private static readonly object lockForSharedMethod = new object();
...
private static void SharedMethod()
{
lock(lockForSharedMethod)
{
// Code in here will only execute in a single thread
}
}
最近,我看到一些人在与类似的代码作斗争。你问如何使用Thread.Join
,而它似乎不是适合这项工作的工具,这一事实表明,有人用糟糕的例子教线程。如果你觉得它有用的话,我会继续向人们推荐——我是对的,那里有一些糟糕的课程——我想鼓励你也分享一下。这会给你一个想法: