C#Threading,我的静态变量没有被锁定

时间:2018-02-24 07:33:29

标签: asp.net multithreading locking

我的应用程序和方法中有很多静态变量可以修改这些变量。请在下面找到示例代码。在下面的例子中,有人可以告诉我如何锁定我的静态变量。它没有被锁定

    using System.Threading;
using System;

namespace ThreadTest
{
    public class Program
    {
        public static void Main(string[] args)
        {
            MyTest.TestVar = 0;
            Thread th = new Thread(ThreadB);
            Thread th1 = new Thread(ThreadC);
            th1.Start();
            Console.WriteLine("Thread B started:");
            th.Start();
            Console.WriteLine("Thread C started :");

            for (int i = 0; i < 10; i++)
            {
                MyTest.TestVar = Convert.ToInt32(MyTest.TestVar) + 1;
                Console.WriteLine("A " + MyTest.TestVar);
                Thread.Sleep(100);
            }

            Console.WriteLine("Threads completed");
        }

        public static void ThreadB()
        {
            lock (MyTest.TestVar)
            {
                for (int i = 0; i < 10; i++)
                {
                MyTest.TestVar = Convert.ToInt32(MyTest.TestVar) + 1;
                Console.WriteLine("B " + MyTest.TestVar);
                    Thread.Sleep(10);
                }
            }
        }

        public static void ThreadC()
        {
            for (int i = 0; i < 10; i++)
            {
                MyTest.TestVar = Convert.ToInt32(MyTest.TestVar) + 1;
                Console.WriteLine("C " + MyTest.TestVar);
                //Thread.Sleep(100);
            }
        }
    }
    public class MyTest
    {
      public static Object TestVar;
    }
}

在此处Initialization Scripts

1 个答案:

答案 0 :(得分:0)

使用var i: Integer; number_profiles: size_t; profiles: ppAnsiChar; ... profiles := MagickGetImageProfiles(wand, pattern, number_profiles); // error checking goes here, as described by API documentation p := profiles; for i := 0 to number_profiles-1 do Writeln(profiles[i]); MagickRelinquishMemory(profiles); 解决您的问题。使用如下的示例代码。

  1. 在控制台应用程序中声明并实例化一个私有对象变量,该变量将用于锁定对TestVar的访问。

    lock statement
  2. 然后,在lock语句中将TestVar加1的语句括起来。

     //declare a private variable for locking
      private  Object obj = new Object() ;
    
  3. 完成上述步骤后,C#runtime将一次只允许一个线程执行更改TestVar值的代码行。