MessageQueueEnumerator Класс

Определение

Предоставляет курсор только для пересылки для перечисления сообщений в очереди сообщений.

public ref class MessageQueueEnumerator : MarshalByRefObject, IDisposable, System::Collections::IEnumerator
public class MessageQueueEnumerator : MarshalByRefObject, IDisposable, System.Collections.IEnumerator
type MessageQueueEnumerator = class
    inherit MarshalByRefObject
    interface IEnumerator
    interface IDisposable
Public Class MessageQueueEnumerator
Inherits MarshalByRefObject
Implements IDisposable, IEnumerator
Наследование
MessageQueueEnumerator
Реализации

Примеры

В следующем примере кода выполняется итерацию по всем очередям сообщений в сети и проверяется путь для каждой очереди. Наконец, он отображает количество общедоступных очередей в сети.

#using <System.dll>
#using <System.Messaging.dll>

using namespace System;
using namespace System::Messaging;

//**************************************************
// Iterates through message queues and examines the
// path for each queue. Also displays the number of
// public queues on the network.
//**************************************************
void ListPublicQueues()
{
   
   // Holds the count of private queues.
   int numberQueues = 0;
   
   // Get a cursor into the queues on the network.
   MessageQueueEnumerator^ myQueueEnumerator = MessageQueue::GetMessageQueueEnumerator();
   
   // Move to the next queue and read its path.
   while ( myQueueEnumerator->MoveNext() )
   {
      
      // Increase the count if priority is Lowest.
      Console::WriteLine( myQueueEnumerator->Current->Path );
      numberQueues++;
   }

   
   // Display final count.
   Console::WriteLine( "Number of public queues: {0}", numberQueues );
   return;
}


//**************************************************
// Provides an entry point into the application.
//   
// This example uses a cursor to step through the
// message queues and list the public queues on the
// network.
//**************************************************
int main()
{
   
   // Output the count of Lowest priority messages.
   ListPublicQueues();
}
using System;
using System.Messaging;

namespace MyProject
{
    /// <summary>
    /// Provides a container class for the example.
    /// </summary>
    public class MyNewQueue
    {

        //**************************************************
        // Provides an entry point into the application.
        //		
        // This example uses a cursor to step through the
        // message queues and list the public queues on the
        // network.
        //**************************************************

        public static void Main()
        {
            // Create a new instance of the class.
            MyNewQueue myNewQueue = new MyNewQueue();

            // Output the count of Lowest priority messages.
            myNewQueue.ListPublicQueues();
                        
            return;
        }

        //**************************************************
        // Iterates through message queues and examines the
        // path for each queue. Also displays the number of
        // public queues on the network.
        //**************************************************
        
        public void ListPublicQueues()
        {
            // Holds the count of private queues.
            uint numberQueues = 0;
    
            // Get a cursor into the queues on the network.
            MessageQueueEnumerator myQueueEnumerator =
                MessageQueue.GetMessageQueueEnumerator();

            // Move to the next queue and read its path.
            while(myQueueEnumerator.MoveNext())
            {
                // Increase the count if priority is Lowest.
                Console.WriteLine(myQueueEnumerator.Current.Path);
                numberQueues++;
            }

            // Display final count.
            Console.WriteLine("Number of public queues: " +
                numberQueues.ToString());
            
            return;
        }
    }
}
Imports System.Messaging



Public Class MyNewQueue


        
        ' Provides an entry point into the application.
        '		 
        ' This example uses a cursor to step through the
        ' message queues and list the public queues on the
        ' network.
        

        Public Shared Sub Main()

            ' Create a new instance of the class.
            Dim myNewQueue As New MyNewQueue()

            ' Output the count of Lowest priority messages.
            myNewQueue.ListPublicQueues()

            Return

        End Sub


        
        ' Iterates through message queues and examines the
        ' path for each queue. Also displays the number of
        ' public queues on the network.
        

        Public Sub ListPublicQueues()

            ' Holds the count of private queues.
            Dim numberQueues As Int32 = 0

            ' Get a cursor into the queues on the network.
            Dim myQueueEnumerator As MessageQueueEnumerator = _
                MessageQueue.GetMessageQueueEnumerator()

            ' Move to the next queue and read its path.
            While myQueueEnumerator.MoveNext()
                ' Increase the count if the priority is Lowest.
                Console.WriteLine(myQueueEnumerator.Current.Path)
                numberQueues += 1
            End While

            ' Display final count.
            Console.WriteLine(("Number of public queues: " + _
                numberQueues.ToString()))

            Return

        End Sub

End Class

Комментарии

Используется MessageQueueEnumerator для динамического взаимодействия с очередями в сети. Методы, доступные через MessageQueue класс, могут возвращать MessageQueueEnumerator либо динамический список очередей, либо массив, содержащий моментальный снимок коллекции очередей во время вызова указанного метода.

В сети нет определенного порядка очередей. Они не упорядочены, например компьютером, меткой, общедоступным или частным состоянием или другими критериями, доступными для пользователей. Это MessageQueueEnumerator курсор, инициализируемый в голову динамического списка. Курсор можно переместить в первую очередь перечисления путем вызова MoveNext. После инициализации перечислителя можно выполнить MoveNext шаг вперед по оставшимся очередям.

Невозможно выполнить шаг назад с помощью MessageQueueEnumerator. Курсор разрешает перемещение только через перечисление очередей. Однако можно вызвать Reset сброс перечисления и снова поместить курсор в начало списка. Так как перечислитель является динамическим, к очереди, добавляемой за пределами текущей позиции курсора, можно получить доступ к перечислителю. Очередь, вставленная перед текущей позицией курсора, не может быть доступна без первого вызова сброса.

Свойства

Имя Описание
Current

Возвращает текущий момент MessageQueue перечисления.

LocatorHandle

Получает собственный дескриптор очереди сообщений, используемый для поиска очередей в сети.

Методы

Имя Описание
Close()

Освобождает ресурсы, связанные с перечислителем.

CreateObjRef(Type)

Создает объект, содержащий все соответствующие сведения, необходимые для создания прокси-сервера, используемого для взаимодействия с удаленным объектом.

(Унаследовано от MarshalByRefObject)
Dispose()

Освобождает все ресурсы, используемые параметром MessageQueueEnumerator.

Dispose(Boolean)

Освобождает неуправляемые ресурсы, используемые MessageQueueEnumerator и при необходимости освобождает управляемые ресурсы.

Equals(Object)

Определяет, равен ли указанный объект текущему объекту.

(Унаследовано от Object)
Finalize()

Освобождает ресурсы, удерживаемые очередью.

GetHashCode()

Служит хэш-функцией по умолчанию.

(Унаследовано от Object)
GetLifetimeService()
Устаревшие..

Извлекает текущий объект службы времени существования, который управляет политикой времени существования для этого экземпляра.

(Унаследовано от MarshalByRefObject)
GetType()

Возвращает Type текущего экземпляра.

(Унаследовано от Object)
InitializeLifetimeService()
Устаревшие..

Получает объект службы времени существования для управления политикой времени существования для этого экземпляра.

(Унаследовано от MarshalByRefObject)
MemberwiseClone()

Создает неглубокую копию текущей Object.

(Унаследовано от Object)
MemberwiseClone(Boolean)

Создает неглубокую копию текущего MarshalByRefObject объекта.

(Унаследовано от MarshalByRefObject)
MoveNext()

Перемещает перечислитель в следующую очередь перечисления, если он доступен в данный момент.

Reset()

Сбрасывает курсор, поэтому указывает на начало перечисления.

ToString()

Возвращает строку, представляющую текущий объект.

(Унаследовано от Object)

Явные реализации интерфейса

Имя Описание
IEnumerator.Current

Возвращает текущий момент MessageQueue перечисления.

Применяется к

См. также раздел