Monitor.TryEnter, méthode (Object) (System.Threading)

Bibliothèque de classes .NET Framework 
Monitor.TryEnter, méthode (Object) 

Essaie d'acquérir un verrou exclusif sur l'objet spécifié.

Espace de noms : System.Threading
Assembly : mscorlib (dans mscorlib.dll)

SyntaxeSyntaxe


Visual Basic (Déclaration)
Public Shared Function TryEnter ( _
    obj As Object _
) As Boolean


Visual Basic (Utilisation)
Dim obj As Object
Dim returnValue As Boolean

returnValue = Monitor.TryEnter(obj)


C#
public static bool TryEnter (
    Object obj
)


C++
public:
static bool TryEnter (
    Object^ obj
)


J#
public static boolean TryEnter (
    Object obj
)


JScript
public static function TryEnter (
    obj : Object
) : boolean

Paramètres

obj

Objet sur lequel acquérir le verrou.

Valeur de retour

true si le thread en cours acquiert le verrou ; sinon, false.
ExceptionsExceptions
Type d'exceptionCondition

ArgumentNullException

Le paramètre obj est référence Null (Nothing en Visual Basic).

ArgumentException

Le paramètre obj est un type valeur.

NotesNotes

Si elle aboutit, cette méthode acquiert un verrou exclusif sur le paramètre obj. Le retour de cette méthode est immédiat, que le verrou soit disponible ou non.

Cette méthode ressemble à Enter, mais elle ne se bloque jamais. Si le thread ne peut pas entrer sans se bloquer, la méthode retourne false, et le thread n'entre pas dans la section critique.

RemarqueRemarque

Utilisez Monitor pour bloquer des objets (c'est-à-dire des types référence), mais pas des types valeur. Pour plus d'informations, consultez Enter et la rubrique conceptuelle Moniteurs.

ExempleExemple

L'exemple de code suivant montre comment utiliser la méthode TryEnter.



Visual Basic
Imports System
Imports System.Threading
Imports System.Collections


Class MonitorSample
    'Define the queue to safe thread access.
    Private m_inputQueue As Queue

    Public Sub New()
        m_inputQueue = New Queue()
    End Sub

    'Add an element to the queue and obtain the monitor lock for the queue object.
    Public Sub AddElement(ByVal qValue As Object)
        'Lock the queue.
        Monitor.Enter(m_inputQueue)
        'Add an element.
        m_inputQueue.Enqueue(qValue)
        'Unlock the queue.
        Monitor.Exit(m_inputQueue)
    End Sub

    'Try to add an element to the queue.
    'Add the element to the queue only if the queue object is unlocked.
    Public Function AddElementWithoutWait(ByVal qValue As Object) As Boolean
        'Determine whether the queue is locked.
        If Not Monitor.TryEnter(m_inputQueue) Then
            Return False
        Else
            m_inputQueue.Enqueue(qValue)
            Monitor.Exit(m_inputQueue)
            Return True
        End If
    End Function

    'Try to add an element to the queue. 
    'Add the element to the queue only if during the specified time the queue object will be unlocked.
    Public Function WaitToAddElement(ByVal qValue As Object, ByVal waitTime As Integer) As Boolean
        'Wait while the queue is locked.
        If Not Monitor.TryEnter(m_inputQueue, waitTime) Then
            Return False
        Else
            m_inputQueue.Enqueue(qValue)
            Monitor.Exit(m_inputQueue)
            Return True
        End If
    End Function

    'Delete all elements that equal the given object and obtain the monitor lock for the queue object.
    Public Sub DeleteElement(ByVal qValue As Object)
        'Lock the queue.
        Monitor.Enter(m_inputQueue)
        Dim counter As Integer = m_inputQueue.Count
        While (counter > 0)    
            'Check each element.
            Dim elm As Object = m_inputQueue.Dequeue()
            If Not elm.Equals(qValue) Then
                m_inputQueue.Enqueue(elm)
            End If
            counter = counter - 1
        End While
        'Unlock the queue.
        Monitor.Exit(m_inputQueue)
    End Sub

    'Print all queue elements.
    Public Sub PrintAllElements()
        'Lock the queue.
        Monitor.Enter(m_inputQueue)
        Dim elmEnum As IEnumerator = m_inputQueue.GetEnumerator()
        While elmEnum.MoveNext()
            'Print the next element.
            Console.WriteLine(elmEnum.Current.ToString())
        End While
        'Unlock the queue.
        Monitor.Exit(m_inputQueue)
    End Sub

    Public Shared Sub Main()
        Dim sample As MonitorSample = New MonitorSample()
        Dim i As Integer

        For i = 0 To 29
            sample.AddElement(i)
        Next i
        sample.PrintAllElements()
        sample.DeleteElement(0)
        sample.DeleteElement(10)
        sample.DeleteElement(20)
        sample.PrintAllElements()
    End Sub

End Class


C#
using System;
using System.Collections;
using System.Threading;

namespace MonitorCS2
{
    /// <summary>
    /// Summary description for Class1.
    /// </summary>
    class MonitorSample
    {
        //Define the queue to safe thread access.
        private Queue m_inputQueue;

        public MonitorSample()
        {
            m_inputQueue = new Queue(); 
        }

        //Add an element to the queue and obtain the monitor lock for the queue object.
        public void AddElement(object qValue)
        {
            //Lock the queue.
            Monitor.Enter(m_inputQueue);
            //Add element
            m_inputQueue.Enqueue(qValue);
            //Unlock the queue.
            Monitor.Exit(m_inputQueue);
        }

        //Try to add an element to the queue.
        //Add the element to the queue only if the queue object is unlocked.
        public bool AddElementWithoutWait(object qValue)
        {
            //Determine whether the queue is locked 
            if(!Monitor.TryEnter(m_inputQueue))
                return false;
            m_inputQueue.Enqueue(qValue);

            Monitor.Exit(m_inputQueue);
            return true;
        }

        //Try to add an element to the queue. 
        //Add the element to the queue only if during the specified time the queue object will be unlocked.
        public bool WaitToAddElement(object qValue, int waitTime)
        {
            //Wait while the queue is locked.
            if(!Monitor.TryEnter(m_inputQueue,waitTime))
                return false;
            m_inputQueue.Enqueue(qValue);
            Monitor.Exit(m_inputQueue);

            return true;
        }
        
        //Delete all elements that equal the given object and obtain the monitor lock for the queue object.
        public void DeleteElement(object qValue)
        {
            //Lock the queue.
            Monitor.Enter(m_inputQueue);
            int counter = m_inputQueue.Count;
            while(counter > 0)
            {    
                //Check each element.
                object elm = m_inputQueue.Dequeue();
                if(!elm.Equals(qValue))
                {
                    m_inputQueue.Enqueue(elm);
                }
                --counter;
            }
            //Unlock the queue.
            Monitor.Exit(m_inputQueue);
        }
        
        //Print all queue elements.
        public void PrintAllElements()
        {
            //Lock the queue.
            Monitor.Enter(m_inputQueue);            
            IEnumerator elmEnum = m_inputQueue.GetEnumerator();
            while(elmEnum.MoveNext())
            {
                //Print the next element.
                Console.WriteLine(elmEnum.Current.ToString());
            }
            //Unlock the queue.
            Monitor.Exit(m_inputQueue);    
        }

        static void Main(string[] args)
        {
            MonitorSample sample = new MonitorSample();
            
            for(int i = 0; i < 30; i++)
                sample.AddElement(i);
            sample.PrintAllElements();
            sample.DeleteElement(0);
            sample.DeleteElement(10);
            sample.DeleteElement(20);
            sample.PrintAllElements();

        }
    }
}


C++
using namespace System;
using namespace System::Collections;
using namespace System::Threading;

// Class definition
public ref class MonitorSample
{
public:
   MonitorSample();
   void AddElement( Object^ qValue );
   bool AddElementWithoutWait( Object^ qValue );
   bool WaitToAddElement( Object^ qValue, int waitTime );
   void DeleteElement( Object^ qValue );
   void PrintAllElements();

private:
   Queue^ m_inputQueue;
};


//Define the queue to safe thread access.
MonitorSample::MonitorSample()
{
   m_inputQueue = gcnew Queue;
}


//Add an element to the queue and obtain the monitor lock for the queue object.
void MonitorSample::AddElement( Object^ qValue )
{
   
   //Lock the queue.
   Monitor::Enter( m_inputQueue );
   
   //Add element
   m_inputQueue->Enqueue( qValue );
   
   //Unlock the queue.
   Monitor::Exit( m_inputQueue );
}


//Try to add an element to the queue.
//Add the element to the queue only if the queue object is unlocked.
bool MonitorSample::AddElementWithoutWait( Object^ qValue )
{
   
   //Determine whether the queue is locked 
   if (  !Monitor::TryEnter( m_inputQueue ) )
      return false;

   m_inputQueue->Enqueue( qValue );
   Monitor::Exit( m_inputQueue );
   return true;
}


//Try to add an element to the queue. 
//Add the element to the queue only if during the specified time the queue object will be unlocked.
bool MonitorSample::WaitToAddElement( Object^ qValue, int waitTime )
{
   
   //Wait while the queue is locked.
   if (  !Monitor::TryEnter( m_inputQueue, waitTime ) )
      return false;

   m_inputQueue->Enqueue( qValue );
   Monitor::Exit( m_inputQueue );
   return true;
}


//Delete all elements that equal the given object and obtain the monitor lock for the queue object.
void MonitorSample::DeleteElement( Object^ qValue )
{
   
   //Lock the queue.
   Monitor::Enter( m_inputQueue );
   int counter = m_inputQueue->Count;
   while ( counter > 0 )
   {
      
      //Check each element.
      Object^ elm = m_inputQueue->Dequeue();
      if (  !elm->Equals( qValue ) )
      {
         m_inputQueue->Enqueue( elm );
      }

      --counter;
   }

   Monitor::Exit( m_inputQueue );
}


//Print all queue elements.
void MonitorSample::PrintAllElements()
{
   
   //Lock the queue.
   Monitor::Enter( m_inputQueue );
   IEnumerator^ elmEnum = m_inputQueue->GetEnumerator();
   while ( elmEnum->MoveNext() )
   {
      
      //Print the next element.
      Console::WriteLine( elmEnum->Current->ToString() );
   }

   Monitor::Exit( m_inputQueue );
}

int main()
{
   MonitorSample^ sample = gcnew MonitorSample;
   for ( int i = 0; i < 30; i++ )
      sample->AddElement( i );
   sample->PrintAllElements();
   sample->DeleteElement( 0 );
   sample->DeleteElement( 10 );
   sample->DeleteElement( 20 );
   sample->PrintAllElements();
}



J#
package MonitorJSL2;

import System.*;
import System.Collections.*;
import System.Threading.*;

/// <summary>
/// Summary description for Class1.
/// </summary>
    
class MonitorSample
{
    //Define the queue to safe thread access.
    private Queue mInputQueue;

    public MonitorSample()
    {
        mInputQueue = new Queue();
    } //MonitorSample

    // Add an element to the queue and obtain the monitor lock for the 
    // queue object.
    public void AddElement(Object qValue)
    {
        //Lock the queue.
        Monitor.Enter(mInputQueue);

        //Add element
        mInputQueue.Enqueue(qValue);

        //Unlock the queue.
        Monitor.Exit(mInputQueue);
    } //AddElement

    //Try to add an element to the queue.
    //Add the element to the queue only if the queue object is unlocked.
    public boolean AddElementWithoutWait(Object qValue)
    {
        //Determine whether the queue is locked 
        if (!(Monitor.TryEnter(mInputQueue))) {
            return false;
        }
        mInputQueue.Enqueue(qValue);
        Monitor.Exit(mInputQueue);
        return true;
    } //AddElementWithoutWait

    //Try to add an element to the queue. 
    //Add the element to the queue only if during the specified time the 
    //queue object will be unlocked.
    public boolean WaitToAddElement(Object qValue, int waitTime)
    {
        //Wait while the queue is locked.
        if (!(Monitor.TryEnter(mInputQueue, waitTime))) {
            return false;
        }
        mInputQueue.Enqueue(qValue);
        Monitor.Exit(mInputQueue);

        return true;
    } //WaitToAddElement

    //Delete all elements that equal the given object and obtain the 
    //monitor lock for the queue object.
    public void DeleteElement(Object qValue)
    {
        //Lock the queue.
        Monitor.Enter(mInputQueue);
        int counter = mInputQueue.get_Count();
        while (counter > 0) {
            //Check each element.
            Object elm = mInputQueue.Dequeue();
            if (!(elm.Equals(qValue))) {
                mInputQueue.Enqueue(elm);
            }
            --counter;
        }

        //Unlock the queue.
        Monitor.Exit(mInputQueue);
    } //DeleteElement

    //Print all queue elements.
    public void PrintAllElements()
    {
        //Lock the queue.
        Monitor.Enter(mInputQueue);
        IEnumerator elmEnum = mInputQueue.GetEnumerator();
        while (elmEnum.MoveNext()) {
            //Print the next element.
            Console.WriteLine(elmEnum.get_Current().ToString());
        }

        //Unlock the queue.
        Monitor.Exit(mInputQueue);
    } //PrintAllElements

    public static void main(String[] args)
    {
        MonitorSample sample = new MonitorSample();

        for (int i = 0; i < 30; i++) {
            sample.AddElement((Int32)i);
        }
        sample.PrintAllElements();
        sample.DeleteElement((Int32)0);
        sample.DeleteElement((Int32)10);
        sample.DeleteElement((Int32)20);
        sample.PrintAllElements();
    } //main 
} //MonitorSample
Plates-formesPlates-formes

Windows 98, Windows 2000 SP4, Windows CE, Windows Millennium Edition, Windows Mobile pour Pocket PC, Windows Mobile pour Smartphone, Windows Server 2003, Windows XP Édition Media Center, Windows XP Professionnel Édition x64, Windows XP SP2, Windows XP Starter Edition

Le .NET Framework ne prend pas en charge toutes les versions de chaque plate-forme. Pour obtenir la liste des versions prises en charge, consultez Configuration requise.

Informations de versionInformations de version

.NET Framework

Prise en charge dans : 2.0, 1.1, 1.0

.NET Compact Framework

Prise en charge dans : 2.0
Voir aussiVoir aussi

Ces informations proviennent du site de http://msdn2.microsoft.com
Source de cette page : http://msdn2.microsoft.com/fr-fr/library/4tssbxcw.aspx

Réseaux sociaux

Vous pouvez modifier vos préférences dans votre profil pour ne plus afficher les interactions avec les réseaux sociaux sur ces pages.

 

Nuage de mots clés

9 mots clés dont 0 définis manuellement (plus d'information...).

Avertissement

Cette page ne possède pas encore de mots clés manuels, ceci est donc un exemple automatique (les niveaux de pertinence sont fictifs, mais les liens sont valables). Pour tester le nuage avec une page qui contient des mots définis manuellement, vous pouvez cliquer ici.

Vous pouvez modifier vos préférences dans votre profil pour ne plus afficher le nuage de mots clés.

 

Astuce pour imprimer les couleurs des cellules de tableaux : http://www.gaudry.be/ast-rf-450.html
Aucun commentaire pour cette page

© Ce document issu de l′infobrol est enregistré sous le certificat Cyber PrInterDeposit Digital Numbertection. Enregistrement IDDN n° 5329-6921
Document créé le 06/11/06 23:38, dernière modification le Vendredi 17 Juin 2011, 12:11
Source du document imprimé : http://www.gaudry.be/dotnet-rf-4tssbxcw.html Document affiché 9 fois ce mois de Mai.
St.Gaudry©07.01.02
Outils (masquer)
||
Recherche (afficher)
Recherche :

Utilisateur (masquer)
Navigation (masquer)
Apparence (afficher)
Stats (afficher)
15832 documents
452 astuces.
549 niouzes.
3099 definitions.
447 membres.
8115 messages.

Document genere en :
0,53 seconde

Mises à jour :
Mises à jour du site
Citation (masquer)
Les ordinateurs sont comme les Dieux de l'Ancien testament : beaucoup de règles et aucune pitié.

Joseph Campbell
 
l'infobrol
Nous sommes le Jeudi 31 Mai 2012, 00:39, toutes les heures sont au format GMT+1.00 Heure, heure d'été (+1)