与问题相关的代码:
CEvent  oEvent;
::WaitForSingleObject(oEvent.m_hObject,INFINITE);问:用 oEvent.Lock();代替上面的::WaitForSingleObject(...)等待事件不可以吗?两者有何区别?

解决方案 »

  1.   

    其实是一样的,因为Lock其实就是对WaitForSingleObject的封装。Lock传入的参数就是WaitForSingleObject的第二个参数.Lock的参数只有一个,缺省值就是INFIINITE(-1).
    你可以读一下MFC的源代码就明白了。CEvent声明在afxmt.h中,实现在mtcore.cpp中.是面也就是对WaitForSingleObject的简单调用,然后判断返回值罢了。
      

  2.   

    An object of class CEvent represents an "event" — a synchronization object that allows one thread to notify another that an event has occurred. Events are useful when a thread needs to know when to perform its task. For example, a thread that copies data to a data archive would need to be notified when new data is available. By using a CEvent object to notify the copy thread when new data is available, the thread can perform its task as soon as possible.CEvent objects have two types: manual and automatic. A manual CEvent object stays in the state set by SetEvent or ResetEvent until the other function is called. An automatic CEvent object automatically returns to a nonsignaled (unavailable) state after at least one thread is released.To use a CEvent object, construct the CEvent object when it is needed. Specify the name of the event you wish to wait on, and that your application should initially own it. You can then access the event when the constructor returns. Call SetEvent to signal (make available) the event object and then call Unlock when you are done accessing the controlled resource.An alternative method for using CEvent objects is to add a variable of type CEvent as a data member to the class you wish to control. During construction of the controlled object, call the constructor of the CEvent data member specifying if the event is initially signaled, the type of event object you want, the name of the event (if it will be used across process boundaries), and desired security attributes.To access a resource controlled by a CEvent object in this manner, first create a variable of either type CSingleLock or type CMultiLock in your resource's access member function. Then call the lock object's Lock member function (for example, CMultiLock::Lock). At this point, your thread will either gain access to the resource, wait for the resource to be released and gain access, or wait for the resource to be released and time out, failing to gain access to the resource. In any case, your resource has been accessed in a thread-safe manner. To release the resource, call SetEvent to signal the event object, and then use the lock object's Unlock member function (for example, CMultiLock::Unlock), or allow the lock object to fall out of scope.