Поделиться через


Метод Observable.ToObservable<TSource> (IEnumerable<TSource>, IScheduler)

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

Пространство имен:System.Reactive.Linq
Сборки: System.Reactive (в System.Reactive.dll)

Синтаксис

'Declaration
<ExtensionAttribute> _
Public Shared Function ToObservable(Of TSource) ( _
    source As IEnumerable(Of TSource), _
    scheduler As IScheduler _
) As IObservable(Of TSource)
'Usage
Dim source As IEnumerable(Of TSource)
Dim scheduler As IScheduler
Dim returnValue As IObservable(Of TSource)

returnValue = source.ToObservable(scheduler)
public static IObservable<TSource> ToObservable<TSource>(
    this IEnumerable<TSource> source,
    IScheduler scheduler
)
[ExtensionAttribute]
public:
generic<typename TSource>
static IObservable<TSource>^ ToObservable(
    IEnumerable<TSource>^ source, 
    IScheduler^ scheduler
)
static member ToObservable : 
        source:IEnumerable<'TSource> * 
        scheduler:IScheduler -> IObservable<'TSource> 
JScript does not support generic types and methods.

Параметры типа

  • TSource
    Тип источника.

Параметры

  • source
    Тип: System.Collections.Generic.IEnumerable<TSource>
    Перечисляемая последовательность, преобразуемая в наблюдаемую последовательность.

Возвращаемое значение

Тип: System.IObservable<TSource>
Наблюдаемая последовательность, элементы которой извлекаются из заданной перечисляемой последовательности.

Примечание об использовании

В Visual Basic и C# этот метод можно вызывать как метод экземпляра для любого объекта типа IEnumerable<TSource>. При вызове метода для экземпляра следует опускать первый параметр. Дополнительные сведения см. в разделе или .

Комментарии

Оператор ToObservable создает наблюдаемую последовательность из объекта, поддерживающего интерфейс IEnumerable. Этот оператор предоставляет параметр планировщика, чтобы разрешить различные параметры планирования для обработки, необходимой для создания наблюдаемой последовательности. Например, может потребоваться запланировать обработку перечисления, необходимую для выполнения в другом потоке.

Примеры

В этом примере создается наблюдаемая последовательность строк (строка> IObservable<) из строки> IEnumerable<, предоставленной массивом строк, возвращенным из System.IO. Метод Directory.GetDirectories. Планировщик ThreadPoolScheduler передается для параметра планировщика оператору ToObservable. Это приведет к выполнению перечисления в потоке из пула потоков .NET. Таким образом, поток main не будет заблокирован.

using System;
using System.IO;
using System.Reactive.Linq;
using System.Reactive.Concurrency;

namespace Example
{
  class Program
  {
    static void Main()
    {
      //*********************************************************************************************************************//
      //*** Create a new observable sequence from the IEnumerable<String> exposed by the string array returned from       ***//
      //*** System.IO.Directory.GetDirectories().                                                                         ***//
      //***                                                                                                               ***//
      //*** In this example we use the ThreadPool scheduler to run the enumeration on a thread in the .NET thread pool.   ***//
      //*** This way our main thread is not blocked by the enumeration and we can process user interaction.               ***//
      //*********************************************************************************************************************//

      var fileList = Directory.GetDirectories(@"C:\Program Files");
      var seqfiles = fileList.ToObservable(Scheduler.ThreadPool);


      //*********************************************************************************************************************//
      //*** We subscribe to this sequence with a lambda expression as the action event handler for the OnNext action. It  ***//
      //*** writes each filename to the console window. A action event handler for the OnCompleted action is also         ***//
      //*** provided to inform the user the sequence has ended and prompt for the ENTER key.                              ***//
      //*********************************************************************************************************************//

      Console.WriteLine("\nCreating subscription. Press ENTER to exit...\n");      
      seqfiles.Subscribe(f => Console.WriteLine(f.ToString()));


      //*********************************************************************************************************************//
      //*** Since we used the ThreadPool scheduler when creating the observable sequence, the enumeration is running on a ***//
      //*** thread from the .NET thread pool. So the main thread is not blocked and can terminate the example if the user ***//
      //*** presses ENTER for a long running enumeration.                                                                 ***//
      //*********************************************************************************************************************//

      Console.ReadLine();
    }
  }
}

Следующие выходные данные были созданы с помощью примера кода.

Creating subscription. Press ENTER to exit...

C:\Program Files\Common Files
C:\Program Files\IIS
C:\Program Files\Internet Explorer
C:\Program Files\Microsoft Games
C:\Program Files\Microsoft Help Viewer
C:\Program Files\Microsoft IntelliType Pro
C:\Program Files\Microsoft LifeCam
C:\Program Files\Microsoft Lync
C:\Program Files\Microsoft Office
C:\Program Files\Microsoft SDKs
C:\Program Files\Microsoft Security Client
C:\Program Files\Microsoft SQL Server
C:\Program Files\Microsoft SQL Server Compact Edition
C:\Program Files\Microsoft Sync Framework
C:\Program Files\Microsoft Synchronization Services
C:\Program Files\Microsoft Visual Studio 10.0
C:\Program Files\Microsoft Visual Studio 9.0
C:\Program Files\Microsoft.NET
C:\Program Files\MSBuild
C:\Program Files\Reference Assemblies
C:\Program Files\Uninstall Information
C:\Program Files\Windows Journal
C:\Program Files\Windows Live
C:\Program Files\Windows Mail
C:\Program Files\Windows Media Components
C:\Program Files\Windows Media Player
C:\Program Files\Windows NT
C:\Program Files\Windows Photo Viewer
C:\Program Files\Windows Portable Devices
C:\Program Files\Windows Sidebar
C:\Program Files\Zune

См. также:

Ссылка

Наблюдаемый класс

Перегрузка ToObservable

Пространство имен System.Reactive.Linq