Lock objects [C # .NET] [Thread] careful use of threads

Lock objects [C # .NET] [Thread] careful use of threads


Suppose I use ThreadPool for a time-consuming work, when I instantiate multiple instances, individuals must be able to perform different their work.


public class DemoClass
{
    private static object s_lock = new object();
    private ulong m_value = 0;

    public void DoWork(string name)
    {
        ThreadPool.QueueUserWorkItem(o =>
        {
            lock (s_lock)
            {
                for (ulong i = 0; i < 1000000; i++)
                {
                    m_value = i;
                    Console.WriteLine(string.Format("{0} method value = {1}", name, m_value));
                    Thread.Sleep(1000);
                }
            }
        });
    }
}

Instantiate the class


internal class Program
{
    private static void Main(string[] args)
    {
        DemoClass c1 = new DemoClass();
        DemoClass c2 = new DemoClass();
        c1.DoWork("NO.1");
        Thread.Sleep(1000);
        c2.DoWork("NO.2");
        Console.ReadKey();
    }
}

Results of the sections of the program are as follows:

SNAGHTML131e0c48

Use the results of static variables locked, so different instances are locked with a reference to the object, which poses a problem whenever a programmer to use this class, non-static method call, the lock will encounter, will be synchronized, This lost our purpose

  • To complete the non-static method in a multi-threaded, to be able to perform their work in different individuals, as long as the static s_lock removed enough.
  • Static methods to ensure thread safety, use static objects to lock, if DoWork is a static method, s_lock do not need to be changed.

The s_lock remove the static execution result

SNAGHTML132b0e1d

If any error, please notify the novice posting him to bear

2010 ~ 2017 C # in the fourth quarter

: Original large column  lock object [C # .NET] [Thread] careful use of threads


Guess you like

Origin www.cnblogs.com/petewell/p/11457888.html