다음을 통해 공유


제목<T>. Dispose 메서드

Subject<T> 클래스의 현재 instance 사용하는 모든 리소스를 해제하고 모든 관찰자 구독을 취소합니다.

네임스페이스:System.Reactive.Subjects
어셈블리: System.Reactive(System.Reactive.dll)

Syntax

'Declaration
Public Sub Dispose
'Usage
Dim instance As Subject

instance.Dispose()
public void Dispose()
public:
virtual void Dispose() sealed
abstract Dispose : unit -> unit 
override Dispose : unit -> unit 
public final function Dispose()

구현

IDisposable.Dispose()

예제

이 예제에서는 주체 클래스를 사용하는 방법을 보여 줍니다. 문자열 형식의 Subject instance 두 개의 예제 뉴스 피드를 구독하는 데 사용됩니다. 이러한 피드는 5초 이하의 간격으로 임의의 뉴스 헤드라인을 게시합니다. 그런 다음, 주체의 관찰 가능한 인터페이스에 대한 두 개의 구독이 만들어져 결합된 데이터 스트림을 받습니다. 한 구독은 데이터 스트림의 각 항목을 "모든 뉴스"로 보고합니다. 다른 구독은 스트림의 각 헤드라인을 필터링하여 로컬 헤드라인만 보고합니다. 구독은 모두 받은 각 헤드라인을 콘솔 창에 씁니다. 사용자가 Enter 키를 누르고 Dispose가 호출되어 두 구독을 모두 취소하면 처리가 종료됩니다.

using System;
using System.Reactive.Linq;
using System.Reactive.Subjects;
using System.Reactive.Concurrency;
using System.Threading;

namespace Example
{
  class Program
  {
    static void Main()
    {
      //*****************************************************************************************************//
      //***                                                                                               ***//
      //*** A subject acts similar to a proxy in that it acts as both a subscriber and a publisher        ***//
      //*** It's IObserver interface can be used to subscribe to multiple streams or sequences of data.   ***//
      //*** The data is then published through it's IObservable interface.                                ***//
      //***                                                                                               ***//
      //*** In this example a simple string based subject is used to subscribe to multiple news feeds     ***//
      //*** that provide random news headlines. Subscribers can then subscribe to the subject's           ***//
      //*** observable interface to observe the data stream(s) or a subset ofthe stream(s). Below we      ***//
      //*** subscribe the subject to two different news headline feeds. Then two subscriptions are        ***//
      //*** created: one for delivery of all news headlines, the other receives only local news headlines ***//
      //***                                                                                               ***//
      //*** A local news headline just contains the newsLocation substring ("in your area.").             ***//
      //***                                                                                               ***//
      //*****************************************************************************************************//

      Subject<string> mySubject = new Subject<string>();


      //*********************************************************//
      //*** Create news feed #1 and subscribe mySubject to it ***//
      //*********************************************************//
      NewsHeadlineFeed NewsFeed1 = new NewsHeadlineFeed("Headline News Feed #1");
      NewsFeed1.HeadlineFeed.Subscribe(mySubject);

      //*********************************************************//
      //*** Create news feed #2 and subscribe mySubject to it ***//
      //*********************************************************//
      NewsHeadlineFeed NewsFeed2 = new NewsHeadlineFeed("Headline News Feed #2");
      NewsFeed2.HeadlineFeed.Subscribe(mySubject);


      Console.WriteLine("Subscribing to news headline feeds.\n\nPress ENTER to exit.\n");

      //*****************************************************************************************************//
      //*** Create a subscription to the subject's observable sequence. This subscription will receive    ***//
      //*** all headlines.                                                                                ***//
      //*****************************************************************************************************//
      IDisposable allNewsSubscription = mySubject.Subscribe(x => 
      {
        Console.WriteLine("Subscription : All news subscription\n{0}\n", x);
      });


      //*****************************************************************************************************//
      //*** Create a subscription to the subject's observable sequence. This subscription will filter for ***//
      //*** only local headlines.                                                                         ***//
      //*****************************************************************************************************//

      IDisposable localNewsSubscription = mySubject.Where(x => x.Contains("in your area.")).Subscribe(x => 
      {
        Console.WriteLine("\n************************************\n" +
                          "***[ Local news headline report ]***\n" +
                          "************************************\n{0}\n\n", x);
      });

      Console.ReadLine();


      //*********************************//
      //*** Cancel both subscriptions ***//
      //*********************************//

      allNewsSubscription.Dispose();
      localNewsSubscription.Dispose();
    }
  }



  //*********************************************************************************//
  //*** The NewsHeadlineFeed class is just a mock news feed in the form of an     ***//
  //*** observable sequence in Reactive Extensions.                               ***//
  //*********************************************************************************//
  class NewsHeadlineFeed
  {
    private string feedName;                     // Feedname used to label the stream
    private IObservable<string> headlineFeed;    // The actual data stream
    private readonly Random rand = new Random(); // Used to stream random headlines.


    //*** A list of predefined news events to combine with a simple location string ***//
    static readonly string[] newsEvents = { "A tornado occurred ",
                                            "Weather watch for snow storm issued ",
                                            "A robbery occurred ",
                                            "We have a lottery winner ",
                                            "An earthquake occurred ",
                                            "Severe automobile accident "};

    //*** A list of predefined location strings to combine with a news event. ***//
    static readonly string[] newsLocations = { "in your area.",
                                               "in Dallas, Texas.",
                                               "somewhere in Iraq.",
                                               "Lincolnton, North Carolina",
                                               "Redmond, Washington"};

    public IObservable<string> HeadlineFeed
    {
      get { return headlineFeed; }
    }

    public NewsHeadlineFeed(string name)
    {
      feedName = name;

      //*****************************************************************************************//
      //*** Using the Generate operator to generate a continous stream of headline that occur ***//
      //*** randomly within 5 seconds.                                                        ***//
      //*****************************************************************************************//
      headlineFeed = Observable.Generate(RandNewsEvent(),
                                         evt => true,
                                         evt => RandNewsEvent(),
                                         evt => { Thread.Sleep(rand.Next(5000)); return evt; },
                                         Scheduler.ThreadPool);
    }


    //****************************************************************//
    //*** Some very simple formatting of the headline event string ***//
    //****************************************************************//
    private string RandNewsEvent()
    {
      return "Feedname     : " + feedName + "\nHeadline     : " + newsEvents[rand.Next(newsEvents.Length)] + 
             newsLocations[rand.Next(newsLocations.Length)];
    }
  }
}

다음 출력은 예제 코드를 사용하여 생성되었습니다.

Subscribing to news headline feeds.

Press ENTER to exit.

Subscription : All news subscription
Feedname     : Headline News Feed #2
Headline     : A robbery occurred somewhere in Iraq.

Subscription : All news subscription
Feedname     : Headline News Feed #2
Headline     : An earthquake occurred in Dallas, Texas.

Subscription : All news subscription
Feedname     : Headline News Feed #1
Headline     : We have a lottery winner in your area.

********************************** [ 지역 뉴스 헤드 라인 보고서 ]********************************** 피드 이름 : 헤드 라인 뉴스 피드 #1 헤드 라인 : 우리는 당신의 지역에 복권 당첨자를 가지고있다.

Subscription : All news subscription
Feedname     : Headline News Feed #2
Headline     : Severe automobile accident Redmond, Washington

Subscription : All news subscription
Feedname     : Headline News Feed #2
Headline     : We have a lottery winner in Dallas, Texas.

Subscription : All news subscription
Feedname     : Headline News Feed #2
Headline     : An earthquake occurred in Dallas, Texas.

Subscription : All news subscription
Feedname     : Headline News Feed #1
Headline     : We have a lottery winner somewhere in Iraq.

Subscription : All news subscription
Feedname     : Headline News Feed #2
Headline     : Severe automobile accident somewhere in Iraq.

Subscription : All news subscription
Feedname     : Headline News Feed #2
Headline     : An earthquake occurred in your area.

********************************** [ 지역 뉴스 헤드 라인 보고서 ]********************************** 피드 이름: 헤드라인 뉴스 피드 #2 헤드라인: 해당 지역에서 지진이 발생했습니다.

참고 항목

참조

Subject<T> 클래스

System.Reactive.Subjects 네임스페이스