C#锁(“字符串")不适用于动态参数吗? [英] C# Lock ("string") not working for dynamic argument?

查看:57
本文介绍了C#锁(“字符串")不适用于动态参数吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用C#锁来阻止代码执行.如果我们在Lock中使用动态字符串输入,则无法正常工作.

I am using C# lock to block code execution. It is not working if we use dynamic string input in Lock.

public class ParameterClass
    {
        public string A = string.Empty;
        public Int64 B = 0;
    }

    class Program
    {
        static void Main(string[] args)
        {
            ParameterClass parm = new ParameterClass { A = "Test", B = 1 };
            Thread thread = new Thread(ThreadFun);
            thread.Start(parm);

            System.Threading.Thread.Sleep(2000);

            parm = new ParameterClass { A = "Test", B = 1 };
            ThreadFun(parm);
        }

        public static void ThreadFun(object para)
        {
            ParameterClass parameter = (ParameterClass)para;
            lock (parameter.B.ToString())
            {
                Console.WriteLine(DateTime.Now);
                System.Threading.Thread.Sleep(20000);
            }
        }
    } 

在这里,我将Thread.Sleep(20000)-20秒放入Lock语句中.我的预期结果是应根据参数锁定代码块.B...

Here , I have put Thread.Sleep(20000) - 20 seconds inside Lock statement. my expected result is the code block should be locked based on parameter.B...

有人可以帮助我继续吗?

Can anyone help me to proceed?

推荐答案

如果需要锁定字符串,则可以使用

If you need to lock upon a string you can use string.Intern on the string. Doing this you lock on the string reference.

lock (string.Intern(parameter.B.ToString()))
{ ... }

但是请注意,这与传统的锁对象(private readonly object)不同,这种类型的锁可以在代码中的任何位置使用,从而可能导致同步问题或死锁.

But be aware what this allows, unlike traditional lock objects (private readonly object) this type of lock can used anywhere in the code, potentially causing synchronization issues or deadlocks.

这篇关于C#锁(“字符串")不适用于动态参数吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆