在C#中的方法锁定方法

2023-09-05 04:06:32 作者:晴空如妍

我有一个类,这三种方法。这个类被多个线程。 我想方法1等待,如果方法2和/或Method3任何线程正在运行。 有什么建议?

 公共类的Class1
{
    公共静态无效方法1()
    {
        对象lockThis =新的对象();

        锁定(lockThis)
        {
            //身体功能
        }
    }

    公共静态无效的方法2()
    {
         //身体功能
    }

    公共静态无效Method3()
    {
         //身体功能
    }
}
 

解决方案

如果我理解正确的,你需要的是这样的:

 静态对象lockMethod2 =新的对象();
静态对象lockMethod3 =新的对象();

公共静态无效方法1()
{
    锁定(lockMethod2)
    锁定(lockMethod3)
    {
        //身体功能
    }
}

公共静态无效的方法2()
{
    锁定(lockMethod2)
    {
        //身体功能
    }
}

公共静态无效Method3()
{
    锁定(lockMethod3)
    {
        //身体功能
    }
}
 
c 复习part1 控制台部分

这使得method3执行,如果方法2正在运行,反之亦然,而方法1必须等待两个。当然,方法2和3将1时运行不运行。

I have one class with these three methods. This class is used by many threads. I would like the Method1 to wait, if Method2 and/or Method3 are running in any threads. Any suggestions?

public class Class1
{
    public static void Method1() 
    {
        Object lockThis = new Object();

        lock (lockThis)
        {
            //Body function
        }
    }

    public static void Method2() 
    {
         //Body function
    }

    public static void Method3() 
    {
         //Body function
    }
}

解决方案

If I understood correctly, you need something like this:

static object lockMethod2 = new object();
static object lockMethod3 = new object();

public static void Method1() 
{
    lock (lockMethod2)
    lock (lockMethod3)
    {
        //Body function
    }
}

public static void Method2() 
{
    lock (lockMethod2)
    {
        //Body function
    }
}

public static void Method3() 
{
    lock (lockMethod3)
    {
        //Body function
    }
}

This allows method3 to execute if method2 is running and vice versa, while method1 must wait for both. Of course, method2 and 3 will not run while 1 is running.