Decription
In this article, I am going to write C# code examples to Lock C# code block based on function’s dynamic argument string using lock and String.Intern, lock and custom String Ref table(String.Intern replacement).
Summary
Lock C# function by Constant String
You can lock the C# code block by using Constant string like below method.
static void Main(string[] args)
{
Thread thread1 = new Thread(ThreadFunction);
thread1.Start();
Thread thread2 = new Thread(ThreadFunction);
thread2.Start();
Console.ReadLine();
}
static void ThreadFunction()
{
lock ("lockKey")
{
Console.WriteLine(DateTime.Now.ToString());
Thread.Sleep(10000);
}
}
Lock C# code block by dynamic argument using String.Intern
You can lock the C# function by using function’s dynamic arguments. Here, you need to use String.Intern to main same string reference.
static void Main(string[] args)
{
string arg = "1";
Thread thread1 = new Thread(ThreadFunction);
thread1.Start(arg);
string arg2 = "1";
Thread thread2 = new Thread(ThreadFunction);
thread2.Start(arg2);
Console.ReadLine();
}
static void ThreadFunction(object arg)
{
lock (String.Intern(arg.ToString()))
{
Console.WriteLine(DateTime.Now.ToString());
Thread.Sleep(10000);
}
}
Lock C# code block by fucntion’s arguments using custom String Ref table
You can lock the C# code block by using function’s arguments using custom String Ref table. Here, we have replaced the String.Intern functionality by maintaining custom Dictionary.
static void Main(string[] args)
{
string arg = "1";
Thread thread1 = new Thread(ThreadFunction);
thread1.Start(arg);
string arg2 = "1";
Thread thread2 = new Thread(ThreadFunction);
thread2.Start(arg2);
Console.ReadLine();
}
static void ThreadFunction(object arg)
{
lock (GetStringReference(arg.ToString()))
{
Console.WriteLine(DateTime.Now.ToString());
Thread.Sleep(10000);
}
}
static List<string> refData = new List<string>();
static string GetStringReference(string val)
{
string retVal = string.Empty;
for (int i = 0; i < refData.Count; i++)
{
if (refData[i].Equals(val))
{
retVal = refData[i];
break;
}
}
if (string.IsNullOrEmpty(retVal))
{
refData.Add(val);
retVal = refData[refData.Count - 1];
}
return retVal;
}
Thanks,
Morgan
Software Developer
Advertisement