The lock keyword s a statement block as a critical section.lock(expression) statement_block
where: expression 
Specifies the object that you want to lock on. expression must be a reference type. 
Typically, expression will either be this, if you want to protect an instance variable, or typeof(class), if you want to protect a static variable (or if the critical section occurs in a static method in the given class). statement_block 
The statements of the critical section. 
Res
lock ensures that one thread does not enter a critical section while another thread is in the critical section of code.//from Msdn

解决方案 »

  1.   

    The lock statement obtains the mutual-exclusion lock for a given object, executes a statement, and then releases the lock. lock-statement: 
    lock ( expression ) embedded-statement 
    The expression of a lock statement must denote a value of a reference-type. An implicit boxing conversion (Section 6.1.5) is never performed for the expression of a lock statement, and thus it is a compile-time error for the expression to denote a value of a value-type.A lock statement of the formlock (x) ...
    where x is an expression of a reference-type, is precisely equivalent toSystem.Threading.Monitor.Enter(x);
    try {
       ...
    }
    finally {
       System.Threading.Monitor.Exit(x);
    }
    except that x is only evaluated once.The System.Type object of a class can conveniently be used as the mutual-exclusion lock for static methods of the class. For example:class Cache
    {
       public static void Add(object x) {
          lock (typeof(Cache)) {
             ...
          }
       }
       public static void Remove(object x) {
          lock (typeof(Cache)) {
             ...
          }
       }
    }
      

  2.   

    lock 关键字将某个语句块标记为临界区。lock(expression) statement_block
    此处: expression 
    指定要锁定的对象。expression 必须是引用类型。 
    通常,如果要保护实例变量,则 expression 为 this;如果要保护 static 变量(或者如果临界区出现在给定类的静态方法中),则 expression 为 typeOf (class)。 statement_block 
    临界区的语句。 
      

  3.   

    临界区是个什么样的概念?
    我在程序中有个Webservers的类category其中有个用户确认的方法checkuser(),和数据初始化的方法DataSynchro()。
    我想用一个progressBar来显示确认和数据初始化的进度。该如何做?
      

  4.   

    首先你要理解一下线程的机制。
    明白了,自然就知道lock是干嘛了。