Lock::Lock

Constrói um lock objeto, opcionalmente, aguardando para adquirir o bloqueio para sempre, para um determinado período de tempo ou não.

template<class T> lock(
   T ^ _object
);
template<class T> lock(
   T ^ _object,
   int _timeout
);
template<class T> lock(
   T ^ _object,
   System::TimeSpan _timeout
);
template<class T> lock(
   T ^ _object,
   lock_later
);

Parâmetros

  • _object
    O objeto a ser bloqueado.

  • _timeout
    Valor de tempo limite em milissegundos ou como um TimeSpan.

Exceções

Lança ApplicationException se a aquisição de bloqueio não ocorrer antes do tempo limite.

Comentários

Os primeiros três formulários do construtor tentam adquirir um bloqueio em _object dentro do período de tempo limite especificado (ou Infinite se nenhum for especificado).

O quarto formulário do construtor não adquirir um bloqueio em _object.lock_lateré membro do lock_when de Enum.Use Lock::acquire ou Lock::try_acquire para adquirir o bloqueio neste caso.

O bloqueio será liberado automaticamente quando o destruidor é chamado.

_objectnão pode ser ReaderWriterLock.Se estiver, resultará um erro do compilador.

Exemplo

Este exemplo usa uma única instância de uma classe por vários threads.A classe usa um bloqueio no próprio para garantir que os acessos a seus dados internos consistentes para cada segmento.O thread principal do aplicativo usa um bloqueio na mesma instância da classe para verificar periodicamente se os threads de trabalho ainda existem e aguarda sair até que todos os threads de trabalho concluíram suas tarefas.

// msl_lock_lock.cpp
// compile with: /clr
#include <msclr/lock.h>

using namespace System;
using namespace System::Threading;
using namespace msclr;

ref class CounterClass {
private:
   int Counter;   

public:
   property int ThreadCount;

   // function called by multiple threads, use lock to keep Counter consistent
   // for each thread
   void UseCounter() {
      try {
         lock l(this); // wait infinitely

         Console::WriteLine("In thread {0}, Counter = {1}", Thread::CurrentThread->ManagedThreadId, 
            Counter);

         for (int i = 0; i < 10; i++) {
            Counter++;
            Thread::Sleep(10);
         }
         
         Console::WriteLine("In thread {0}, Counter = {1}", Thread::CurrentThread->ManagedThreadId, 
            Counter);

         Counter = 0;
         // lock is automatically released when it goes out of scope and its destructor is called
      }
      catch (...) {
         Console::WriteLine("Couldn't acquire lock!");
      }

      ThreadCount--;
   }
};

int main() {
   // create a few threads to contend for access to the shared data
   CounterClass^ cc = gcnew CounterClass;
   array<Thread^>^ tarr = gcnew array<Thread^>(5);
   ThreadStart^ startDelegate = gcnew ThreadStart(cc, &CounterClass::UseCounter);
   for (int i = 0; i < tarr->Length; i++) {
      tarr[i] = gcnew Thread(startDelegate);
      cc->ThreadCount++;
      tarr[i]->Start();
   }

   // keep our main thread alive until all worker threads have completed
   lock l(cc, lock_later); // don't lock now, just create the object
   while (true) {
      if (l.try_acquire(50)) { // try to acquire lock, don't throw an exception if can't
         if (0 == cc->ThreadCount) {
            Console::WriteLine("All threads completed.");
            break; // all threads are gone, exit while
         }
         else {
            Console::WriteLine("{0} threads exist, continue waiting...", cc->ThreadCount);
            l.release(); // some threads exist, let them do their work
         }
      }
   }
}
  

Requisitos

Arquivo de cabeçalho <msclr\lock.h>

Namespace msclr

Consulte também

Referência

bloqueio:: ~ lock

Lock::acquire

Lock::try_acquire

Outros recursos

Bloquear membros