c# - 在让其他线程调用它之前让当前线程完成使用该函数 C#

标签 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 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/

相关文章:

c# - Parallel.ForEach 中长时间运行进程的进度条

c# - 为什么使用NEST使用自定义分析器排序的嵌套ElasticSearch返回无效结果?

c# - 遍历具有特定主题的 Outlook 电子邮件

java - 为什么这种形式的 block 同步比其他形式更快?

swift - 在 Swift 中休眠或延迟 Timer 线程

c# - Task.Run() 和 Task.Factory.StartNew() 有什么区别

c# - 线程与任务中的 ThreadStatic 属性

c# - 从命令行打开 Chrome 并等待它关闭

c# - 在每个函数中使用 DataContext

c# - ITravelLogStg::TravelTo 失败并出现错误 0x80004002