Interlocked.Increment, méthode (Int32) (System.Threading)

Bibliothèque de classes .NET Framework 
Interlocked.Increment, méthode (Int32) 

Incrémente une variable spécifiée et stocke le résultat sous la forme d'une opération atomique.

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

SyntaxeSyntaxe


Visual Basic (Déclaration)
Public Shared Function Increment ( _
    ByRef location As Integer _
) As Integer


Visual Basic (Utilisation)
Dim location As Integer
Dim returnValue As Integer

returnValue = Interlocked.Increment(location)


C#
public static int Increment (
    ref int location
)


C++
public:
static int Increment (
    int% location
)


J#
public static int Increment (
    /** @ref */ int location
)


JScript
JScript ne prend pas en charge le passage d'arguments de type valeur par référence.

Paramètres

location

Variable dont la valeur doit être incrémentée.

Valeur de retour

Valeur incrémentée.
ExceptionsExceptions
Type d'exceptionCondition

NullReferenceException

L'adresse de location est un pointeur null.

NotesNotes

Cette méthode gère une condition de dépassement à l'aide de l'encapsulation : si location = Int32.MaxValue, location +1 = Int32.MinValue. Aucune exception n'est levée.

ExempleExemple

L'exemple de code suivant illustre une méthode thread-safe pour l'incrémentation et la décrémentation d'une valeur entière. La valeur de SafeInstanceCount sera toujours zéro. Toutefois, la valeur de UnsafeInstanceCount ne sera pas nécessairement zéro car une condition de concurrence critique survient entre l'incrémentation et la décrémentation du compteur. Cet effet est particulièrement prononcé sur des ordinateurs multiprocesseurs.



Visual Basic
Imports Microsoft.VisualBasic
Imports System
Imports System.Threading

Public Class Test

    <MTAThread> _
    Shared Sub Main()
        Dim thread1 As New Thread(AddressOf ThreadMethod)
        Dim thread2 As New Thread(AddressOf ThreadMethod)
        thread1.Start()
        thread2.Start()
        thread1.Join()
        thread2.Join()

        ' Have the garbage collector run the finalizer for each
        ' instance of CountClass and wait for it to finish.
        GC.Collect()
        GC.WaitForPendingFinalizers()

        Console.WriteLine("UnsafeInstanceCount: {0}" & _
            vbCrLf & "SafeCountInstances: {1}", _
            CountClass.UnsafeInstanceCount.ToString(), _
            CountClass.SafeInstanceCount.ToString())
   End Sub

   Shared Sub ThreadMethod()
        Dim cClass As CountClass 

        ' Create 100,000 instances of CountClass.
        For i As Integer = 1 To 100000
            cClass = New CountClass()
            cClass = Nothing
            i += 1
        Next i
   End Sub

End Class

Public Class CountClass

    Shared unsafeCount As Integer = 0
    Shared   safeCount As Integer = 0

    Shared ReadOnly Property UnsafeInstanceCount As Integer
        Get
            Return unsafeCount
        End Get
    End Property

    Shared ReadOnly Property SafeInstanceCount As Integer
        Get
            Return safeCount
        End Get
    End Property
   
    Sub New()
        unsafeCount += 1
        Interlocked.Increment(safeCount)
    End Sub

    Protected Overrides Sub Finalize()
        unsafeCount -= 1
        Interlocked.Decrement(safeCount)
        MyBase.Finalize()
    End Sub

End Class


C#
using System;
using System.Threading;

class Test
{
    static void Main()
    {
        Thread thread1 = new Thread(new ThreadStart(ThreadMethod));
        Thread thread2 = new Thread(new ThreadStart(ThreadMethod));
        thread1.Start();
        thread2.Start();
        thread1.Join();
        thread2.Join();

        // Have the garbage collector run the finalizer for each
        // instance of CountClass and wait for it to finish.
        GC.Collect();
        GC.WaitForPendingFinalizers();

        Console.WriteLine("UnsafeInstanceCount: {0}" +
            "\nSafeCountInstances: {1}",
            CountClass.UnsafeInstanceCount.ToString(),
            CountClass.SafeInstanceCount.ToString());
    }

    static void ThreadMethod()
    {
        CountClass cClass;
        
        // Create 100,000 instances of CountClass.
        for(int i = 0; i < 100000; i++)
        {
            cClass = new CountClass();
        }
    }
}

class CountClass
{
    static int unsafeInstanceCount = 0;
    static int   safeInstanceCount = 0;

    static public int UnsafeInstanceCount
    {
        get {return unsafeInstanceCount;}
    }

    static public int SafeInstanceCount
    {
        get {return safeInstanceCount;}
    }

    public CountClass()
    {
        unsafeInstanceCount++;
        Interlocked.Increment(ref safeInstanceCount);
    }

    ~CountClass()
    {
        unsafeInstanceCount--;
        Interlocked.Decrement(ref safeInstanceCount);
    }
}


C++
using namespace System;
using namespace System::Threading;
ref class CountClass
{
private:
   static int unsafeInstanceCount;
   static int safeInstanceCount;

public:

   static property int UnsafeInstanceCount 
   {
      int get()
      {
         return unsafeInstanceCount;
      }

   }

   static property int SafeInstanceCount 
   {
      int get()
      {
         return safeInstanceCount;
      }

   }
   CountClass()
   {
      unsafeInstanceCount++;
      Interlocked::Increment( safeInstanceCount );
   }

   ~CountClass()
   {
      unsafeInstanceCount--;
      Interlocked::Decrement( safeInstanceCount );
   }

};

ref class Test
{
public:
   static void ThreadMethod()
   {
      CountClass^ cClass;
      
      // Create 100,000 instances of CountClass.
      for ( int i = 0; i < 100000; i++ )
      {
         cClass = gcnew CountClass;

      }
   }

};

int main()
{
   Thread^ thread1 = gcnew Thread( gcnew ThreadStart( &Test::ThreadMethod ) );
   Thread^ thread2 = gcnew Thread( gcnew ThreadStart( &Test::ThreadMethod ) );
   thread1->Start();
   thread2->Start();
   thread1->Join();
   thread2->Join();
   
   // Have the garbage collector run the finalizer for each
   // instance of CountClass and wait for it to finish.
   GC::Collect();
   GC::WaitForPendingFinalizers();
   Console::WriteLine( "UnsafeInstanceCount: {0}"
   "\nSafeCountInstances: {1}", CountClass::UnsafeInstanceCount.ToString(), CountClass::SafeInstanceCount.ToString() );
}



J#
import System.*;
import System.Threading.*;
import System.Threading.Thread;

class Test
{
    public static void main(String[] args)
    {
        Thread thread1 = new Thread(new ThreadStart(ThreadMethod));
        Thread thread2 = new Thread(new ThreadStart(ThreadMethod));

        thread1.Start();
        thread2.Start();
        thread1.Join();
        thread2.Join();

        // Have the garbage collector run the finalizer for each
        // instance of CountClass and wait for it to finish.
        GC.Collect();
        GC.WaitForPendingFinalizers();
        Console.WriteLine("UnsafeInstanceCount: {0}" + 
            "\nSafeCountInstances: {1}", 
            String.valueOf(CountClass.get_UnsafeInstanceCount()), 
            String.valueOf(CountClass.get_SafeInstanceCount()));
    } //main

    static void ThreadMethod()
    {
        CountClass cClass;

        // Create 100,000 instances of CountClass.
        for (int i = 0; i < 100000; i++) {
            cClass = new CountClass();
        }
    } //ThreadMethod
} //Test

class CountClass
{
    private static int unsafeInstanceCount = 0;
    private static int safeInstanceCount = 0;

    /** @property
     */
    public static int get_UnsafeInstanceCount()
    {
        return unsafeInstanceCount;
    } //get_UnsafeInstanceCount

    /** @property
     */
    public static int get_SafeInstanceCount()
    {
        return safeInstanceCount;
    } //get_SafeInstanceCount

    public CountClass()
    {
        unsafeInstanceCount++;
        Interlocked.Increment(safeInstanceCount);
    } //CountClass

    public void finalize()
    {
        try {
            unsafeInstanceCount--;
            Interlocked.Decrement(safeInstanceCount);
            super.finalize();
        }
        catch (Throwable th) { 
        }
    } //finalize
}  //CountClass
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, 1.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/dd78zt0c.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

10 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-6915
Document créé le 06/11/06 23:33, dernière modification le Vendredi 17 Juin 2011, 12:11
Source du document imprimé : http://www.gaudry.be/dotnet-rf-dd78zt0c.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,92 seconde

Mises à jour :
Mises à jour du site
Citation (masquer)
Je pense que beaucoup de gens sont bons dans bien plus de domaines que ce que le monde ne leur laisse l'opportunité d'exploiter.

Ethan Hawke
 
l'infobrol
Nous sommes le Jeudi 31 Mai 2012, 12:24, toutes les heures sont au format GMT+1.00 Heure, heure d'été (+1)