我似乎无法让 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 作为它们的主要功能。然后,这些主要功能将调用一个共享功能,该功能将在此处使用我的打印机打印我的结果。问题似乎是打印机仍在忙于从前一个线程接收数据/打印结果,但新的当前线程过早进入,导致打印机无法打印下一个结果。有帮助吗?
最佳答案
听起来你只是想要一个锁,为你锁定其监视器的对象使用一个静态字段:
private static readonly object lockForSharedMethod = new object();
...
private static void SharedMethod()
{
lock(lockForSharedMethod)
{
// Code in here will only execute in a single thread
}
}
关于c# - 在让其他线程调用它之前让当前线程完成使用该函数 C#,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47567692/