当前位置: 首页>>代码示例>>C#>>正文


C# CompositeDisposable.Dispose方法代码示例

本文整理汇总了C#中System.Linq.CompositeDisposable.Dispose方法的典型用法代码示例。如果您正苦于以下问题:C# CompositeDisposable.Dispose方法的具体用法?C# CompositeDisposable.Dispose怎么用?C# CompositeDisposable.Dispose使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在System.Linq.CompositeDisposable的用法示例。


在下文中一共展示了CompositeDisposable.Dispose方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。

示例1: SelectDisposableShouldWork

        public void SelectDisposableShouldWork()
        {
            var scheduler = new TestScheduler();
            var disposables = new List<BooleanDisposable>();
            var list = new CompositeDisposable();
            scheduler.CreateColdObservable(
                new Recorded<Notification<long>>(100, Notification.CreateOnNext(0L)),
                new Recorded<Notification<long>>(200, Notification.CreateOnNext(1L)),
                new Recorded<Notification<long>>(300, Notification.CreateOnNext(2L)),
                new Recorded<Notification<long>>(400, Notification.CreateOnNext(3L)),
                new Recorded<Notification<long>>(400, Notification.CreateOnCompleted<long>())
            )
            .SelectDisposable(list, i => {
                var d = new BooleanDisposable();
                disposables.Add(d);
                return d;
            }, (i, _) => i)
            .Subscribe()
            .DisposeWith(list);

            scheduler.AdvanceTo(300);

            disposables.Count.Should().Be(3);

            disposables.Select(d => d.IsDisposed).Should().NotContain(true);

            list.Dispose();

            disposables.Select(d => d.IsDisposed).Should().NotContain(false);

        }
开发者ID:Weingartner,项目名称:SolidworksAddinFramework,代码行数:31,代码来源:DisposableExtensionsSpec.cs

示例2: Run

    public static void Run()
    {
      var systems = new[] { "A", "B", "C" }.Select(CreateExternalSystem);
      var observables = systems.Select(s => s.ObserveHealth()).Select(obs => obs.DistinctUntilChanged(c => c.IsAvailable)).ToList();
      var disposable = new CompositeDisposable();

      // observe independently
      disposable.Add(new CompositeDisposable(observables.Select(c => c.Subscribe(PrintHealthCheck))));

      // merge
      var merged = observables.Aggregate((l, r) => l.Merge(r));
      disposable.Add(merged.Subscribe(PrintHealthCheck));

      // combine
      var combined = observables
        .Aggregate(Observable.Return(Enumerable.Empty<HealthCheck>()), (agg, obs) => agg.CombineLatest(obs, (checks, check) => checks.Concat(new[] { check })));

      var scan = merged.Scan(ImmutableDictionary<string, bool>.Empty, (d, check) => d.SetItem(check.ExternalSystemName, check.IsAvailable));
      
      disposable.Add(combined.Subscribe(e => Console.WriteLine("Combined: " + string.Join(", ", e.Select(c => $"{c.ExternalSystemName}={c.IsAvailable}")))));
      disposable.Add(scan.Subscribe(d => Console.WriteLine("Scanned: " + string.Join(", ", d.Select(p => $"{p.Key}={p.Value}")))));

      Console.ReadKey();
      disposable.Dispose();
    }
开发者ID:MrWolfZ,项目名称:TechTalk-2015-11-27,代码行数:25,代码来源:Solution.cs

示例3: GetServers

 public async Task<IObservable<ArmaServerInfo>> GetServers(CancellationToken ct, ServerFilterWrap filter) {
     var dsp = new CompositeDisposable();
     // Apparently we get null ServerInfo (not even endpoints :S)
     var obs = ServerResponses
         .TakeUntil(RefreshComplete)
         .Select(x => x.ServerInfo == null ? null : ArmaServerInfo.FromWrap(x.ServerIndex, x.ServerInfo))
         .Where(x => x != null)
         .Replay();
     dsp.Add(obs.Connect());
     obs.Subscribe(_ => { }, x => dsp.Dispose(), dsp.Dispose, ct);
     ct.Register(dsp.Dispose);
     await GetServerInfo(filter).ConfigureAwait(false);
     return obs;
 }
开发者ID:SIXNetworks,项目名称:withSIX.Desktop,代码行数:14,代码来源:ServerBrowser.cs

示例4: InputModel

        static InputModel()
        {
            _disposables = new CompositeDisposable();
            _core = new InputCoreModel();
            _accounts = new AccountSelectorModel(_core);

            // link property changing
            var icmpc = new PropertyChangedEventListener(_core);
            icmpc.RegisterHandler(() => _core.CurrentInputData,
                                (o, e) => _accounts.CurrentInputDataChanged());
            _disposables.Add(icmpc);
            SetEventPropagation();

            App.ApplicationFinalize += () => _disposables.Dispose();
        }
开发者ID:Mojopon,项目名称:StarryEyes,代码行数:15,代码来源:InputModel.cs

示例5: PrepareListener

 private IConnectableObservable<ArmaServerInfo> PrepareListener(CancellationToken ct, bool inclRules = false) {
     var dsp = new CompositeDisposable();
     var obs = BuildListener(dsp);
     if (inclRules)
         obs = obs
             .SelectMany(async si => {
                 await UpdateRules(si, ct).ConfigureAwait(false);
                 return si;
             });
     var theObs = obs.Select(x => x.Info)
         .Replay();
     dsp.Add(theObs.Connect());
     theObs.Subscribe(_ => { }, x => dsp.Dispose(), dsp.Dispose, ct);
     ct.Register(dsp.Dispose);
     return theObs;
 }
开发者ID:SIXNetworks,项目名称:withSIX.Desktop,代码行数:16,代码来源:ServerBrowser.cs

示例6: Order

 public void Order()
 {
     // It is time-dependent test (i.e. lengthy and inconsistent), which is not very good but we cannot use HistoricalScheduler to test it...
     var s = Scheduler.ThreadPool;
     var l = new List<int> ();
     var dis = new CompositeDisposable ();
     try {
         dis.Add (s.Schedule (() => { Thread.Sleep (1200); l.Add (1); }));
         dis.Add (s.Schedule (() => { Thread.Sleep (800); l.Add (2); }));
         dis.Add (s.Schedule (() => { Thread.Sleep (50); l.Add (3); }));
         Thread.Sleep (1500);
         Assert.AreEqual (new int [] {3, 2, 1}, l.ToArray (), "#1");
     } finally {
         dis.Dispose ();
     }
 }
开发者ID:paulcbetts,项目名称:mono-reactive,代码行数:16,代码来源:ThreadPoolSchedulerTest.cs

示例7: CompositeDisposable

        private static void CompositeDisposable()
        {
            Demo.DisplayHeader("The CompositeDisposable - groups multiple disposables and dispose them together");

            var compositeDisposable = new CompositeDisposable(
                Disposable.Create(() => Console.WriteLine("1st disposed")),
                Disposable.Create(() => Console.WriteLine("2nd disposed")));

            compositeDisposable.Dispose();

            //The same can also be written using the Add() method
            compositeDisposable = new CompositeDisposable();
            compositeDisposable.Add(Disposable.Create(() => Console.WriteLine("1st disposed")));
            compositeDisposable.Add(Disposable.Create(() => Console.WriteLine("2nd disposed")));

            compositeDisposable.Dispose();
        }
开发者ID:tamirdresher,项目名称:RxInAction,代码行数:17,代码来源:Program.cs

示例8: Order

 public void Order()
 {
     // It is time-dependent test (i.e. lengthy and inconsistent), which is not very good but we cannot use HistoricalScheduler to test it...
     var s = Scheduler.TaskPool;
     var l = new List<int> ();
     var dis = new CompositeDisposable ();
     try {
         // If the tasks do not run long enough, the (Task) scheduler will not use separate Threads,
         // therefore Thread.Sleep(x) will block not only current task, but also tasks scheduled to run
         // in the same Thread
         dis.Add (s.Schedule (() => { Thread.Sleep (2400); l.Add (1); }));
         dis.Add (s.Schedule (() => { Thread.Sleep (1600); l.Add (2); }));
         dis.Add (s.Schedule (() => { Thread.Sleep (50); l.Add (3); }));
         Thread.Sleep (2500);
         Assert.AreEqual (new int [] {3, 2, 1}, l.ToArray (), "#1");
     } finally {
         dis.Dispose ();
     }
 }
开发者ID:steve-s,项目名称:mono-reactive,代码行数:19,代码来源:TaskPoolSchedulerTest.cs

示例9: Run

    public static void Run()
    {
      var systems = new[] { "A", "B", "C" }.Select(CreateExternalSystem);
      var observables = systems.Select(s => s.ObserveHealth()).Select(obs => obs.DistinctUntilChanged(c => c.IsAvailable)).ToList();
      var disposable = new CompositeDisposable();

      // observe independently
      disposable.Add(new CompositeDisposable(observables.Select(c => c.Subscribe(PrintHealthCheck))));

      // merge
      var merged = Observable.Empty<HealthCheck>();
      disposable.Add(merged.Subscribe(PrintHealthCheck));

      // combine
      var combined = Observable.Empty<IEnumerable<HealthCheck>>();

      disposable.Add(combined.Subscribe(e => Console.WriteLine("Combined: " + string.Join(", ", e.Select(c => $"{c.ExternalSystemName}={c.IsAvailable}")))));

      Console.ReadKey();
      disposable.Dispose();
    }
开发者ID:MrWolfZ,项目名称:TechTalk-2015-11-27,代码行数:21,代码来源:Template.cs

示例10: Main

        static void Main(string[] args)
        {
            AppDomain.CurrentDomain.UnhandledException += (sender, e) => Console.Error.WriteLine(e.ExceptionObject);

            if (args.Length >= 0)
            {
                JsConfig.DateHandler = JsonDateHandler.ISO8601;

                string host = args.Length == 0 ? "localhost" : args.First();

                var redisClient = new RedisClient(host);
                var temprc = redisClient.As<TemperatureItem>();
                var rtempList = temprc.Lists["tempatureReadings"];

                //Console.WriteLine(temprc.GetAllItemsFromList(rtempList).First().Timestamp);
                //Console.WriteLine(temprc.GetAllItemsFromList(rtempList).Last().Temperature);

                Console.WriteLine(string.Join("\n", UsbTEMPer.FindDevices().ToArray()));
                var xs = new ObservableUsbTemper();
                var temps = xs.TemperatureStreamFarenheight
                              .Timestamp()
                              .Do(ts => Console.WriteLine(ts));

                var sub = temps.Select(TemperatureItem.FromTDS)
                               .Subscribe(tst => temprc.AddItemToList(rtempList, tst), Console.Error.WriteLine, () => { });

                var disp = new CompositeDisposable(xs, redisClient, sub);
                Console.ReadKey();
                disp.Dispose();
            }
            else
            {
                ServiceBase.Run(new ServiceBase[]
                {
                    new TempLoggerService()
                });
            }
        }
开发者ID:ScottWeinstein,项目名称:TemperatureLogger,代码行数:38,代码来源:Program.cs

示例11: Impl

        static void Impl(int disposeAt)
        {
            var rand = new Random();

            var g = new CompositeDisposable();

            Console.Write("Dispose @ = {0} - ", disposeAt);

            if (disposeAt == 0)
            {
                g.Dispose();
                Console.Write("{GD} ");
            }

            if (disposeAt == 1)
            {
                var sleep = rand.Next(0, 5) > 1 /* 60% chance */ ? rand.Next(2, 1000) : 0;

                ThreadPool.QueueUserWorkItem(_ =>
                {
                    Helpers.SleepOrSpin(sleep);
                    g.Dispose();
                    Console.Write("{GD} ");
                });
            }

            var n = rand.Next(0, 1000);
            var cd = new CountdownEvent(n);

            var ds = Enumerable.Range(0, n).Select(_ => Disposable.Create(() => cd.Signal())).ToArray();

            var m = rand.Next(1, 100);
            var jobs = ds.GroupBy(_ => rand.Next() % m).Select(Enumerable.ToList).ToList();

            Console.Write("N = {0}, M = {1} - ", n, m);

            var done = new CountdownEvent(jobs.Count);

            foreach (var job in jobs)
            {
                var sleep = rand.Next(0, 10) == 0 /* 10% chance */ ? rand.Next(2, 100) : 0;
                var sleepAt = Enumerable.Range(0, rand.Next(0, job.Count) / rand.Next(1, 100)).ToArray();
                var sleeps = sleepAt.Select(_ => rand.Next(0, 50)).ToArray();

                var rem = rand.Next(0, 3) == 0; /* 33% chance */
                var remAt = rand.Next(0, 10) == 0 /* 10% chance */ ? rand.Next(2, 100) : 0;

                var mine = job;
                ThreadPool.QueueUserWorkItem(_ =>
                {
                    Helpers.SleepOrSpin(sleep);

                    var j = 0;
                    foreach (var d in mine)
                    {
                        var dd = d;

                        if (sleepAt.Contains(j))
                            Helpers.SleepOrSpin(sleeps[j]);

                        g.Add(dd);
                        Console.Write("+");

                        if (rem)
                        {
                            ThreadPool.QueueUserWorkItem(__ =>
                            {
                                Helpers.SleepOrSpin(remAt);
                                g.Remove(dd);
                                Console.Write("-");
                            });
                        }

                        j++;
                    }

                    done.Signal();
                });
            }

            done.Wait();

            if (disposeAt == 2)
            {
                g.Dispose();
                Console.Write("{GD} ");
            }

            cd.Wait();

            Console.WriteLine(".");
        }
开发者ID:Balharmander123,项目名称:Rx.NET,代码行数:92,代码来源:Composite.cs

示例12: CreateNewCompositeDisposable

 /// <summary>
 /// We need to create a new CompositeDisposable, as once a CompositeDisposable is Disposed
 /// it is useless, and we must recreate it
 /// </summary>
 public static void CreateNewCompositeDisposable(ref CompositeDisposable compositeDisposable)
 {
     compositeDisposable.Dispose();
     compositeDisposable = new CompositeDisposable();
 }
开发者ID:joobn72,项目名称:WpfVMBehaviours,代码行数:9,代码来源:DisposableHelper.cs

示例13: StartEditing

        private static void StartEditing(ListView list, ListViewItem item, DocumentGroup group, Action<TextBox, bool> endEditingFn)
        {
            var edit = item.FindDescendant<TextBox>();

            var visibility = Observable.FromEventPattern<DependencyPropertyChangedEventArgs>(edit, "IsVisibleChanged");

            var disposables = new CompositeDisposable();

            visibility.Where(re => re.EventArgs.NewValue as bool? == false)
                      .Take(1)
                      .Subscribe(re => disposables.Dispose());

            visibility.Where(ivc => ivc.EventArgs.NewValue as bool? == true)
                      .Take(1)
                      .Subscribe(re =>
                                 {
                                     edit.SelectionStart = 0;
                                     edit.SelectionLength = edit.Text.Length;
                                     edit.Focus();
                                 });

            disposables.Add(Observable.FromEventPattern<RoutedEventArgs>(edit, "LostFocus")
                                      .Take(1)
                                      .Subscribe(re => endEditingFn(edit, false)));

            disposables.Add(Observable.FromEventPattern<KeyEventArgs>(edit, "PreviewKeyUp")
                                      .Where(re => re.EventArgs.Key == Key.Escape || re.EventArgs.Key == Key.Enter)
                                      .Take(1)
                                      .Subscribe(re =>
                                                 {
                                                     re.EventArgs.Handled = true;
                                                     endEditingFn(edit, re.EventArgs.Key == Key.Escape);
                                                 }));

            disposables.Add(Observable.FromEventPattern<MouseEventArgs>(list, "MouseLeftButtonDown")
                                      .Take(1)
                                      .Subscribe(re => endEditingFn(edit, false)));

            group.StartEditing();
        }
开发者ID:k4gdw,项目名称:SaveAllTheTabs,代码行数:40,代码来源:SavedTabsToolWindowControl.xaml.cs

示例14: TextViewCreated

        public void TextViewCreated(IWpfTextView textView)
        {
            var textBuffer = textView.TextBuffer;

            _openTextViewList.Add(textView);

            var changed = Observable.FromEventPattern<TextContentChangedEventArgs>(x => textBuffer.Changed += x, x => textBuffer.Changed -= x);

            var disp = changed
                .Select(_ => Unit.Default)
                .Multicast(_changed)
                .Connect();

            #if FALSE
            // NB: This feature is too fucked right now
            var disp = new CompositeDisposable(
                changed
                    .Select(_ => Unit.Default)
                    .Multicast(_changed)
                    .Connect(),
                changed.Buffer(() => changed.Throttle(TimeSpan.FromSeconds(2.0), RxApp.TaskpoolScheduler))
                    .ObserveOn(RxApp.MainThreadScheduler)
                    .TakeWhile(_ => textBuffer.CheckEditAccess()) // NB: Kill this if we can't access from the main thread
                    .Subscribe(x => {
                        // Tracking the changes themselves is Hard, because
                        // changes can modify themselves (i.e. you can hit space,
                        // then backspace). Instead, we're going to try to figure
                        // out the entire region that has changed, then apply
                        // trimming to the entire thing, brute force style.
                        var changesWithArgs = x.SelectMany(y =>
                            y.EventArgs.Changes.Select(z => new { Change = z, EventArgs = y.EventArgs }));

                        var minMax = changesWithArgs.Aggregate(new int?[2], (acc, y) => {
                            var smallestInThisChange = Math.Min(y.Change.NewSpan.Start, y.EventArgs.After.GetLineFromPosition(y.Change.NewSpan.Start).Start.Position);
                            var largestInThisChange = Math.Max(y.Change.NewSpan.End, y.EventArgs.After.GetLineFromPosition(y.Change.NewSpan.End).End.Position);

                            acc[0] = Math.Min(acc[0] ?? Int32.MaxValue, smallestInThisChange);
                            acc[1] = Math.Max(acc[1] ?? Int32.MinValue, largestInThisChange);

                            if (y.Change.LineCountDelta > 0) {
                                acc[1] = acc[1].Value + y.Change.LineCountDelta;
                            }

                            return acc;
                        });

                        // NB: I have no idea how this can happen, but it sure
                        // does, every time you edit a Razor view
                        if (!minMax[0].HasValue || !minMax[1].HasValue) return;

                        // Make triple sure we don't run off the end of the buffer
                        minMax[1] = Math.Min(minMax[1].Value, textBuffer.CurrentSnapshot.Length);

                        // NB: Sometimes, Visual Studio decides to submit the
                        // entire document as a "Change" when it really isn't.
                        // We're going to ignore this case even though sometimes
                        // it's actually legit (i.e. if the user pastes in the
                        // entire file).
                        if ((double)(minMax[1].Value - minMax[0].Value) / (double)textBuffer.CurrentSnapshot.Length > 0.9) {
                            return;
                        }

                        var span = textBuffer.CurrentSnapshot.CreateTrackingSpan(minMax[0].Value, minMax[1].Value - minMax[0].Value, SpanTrackingMode.EdgeInclusive).GetSpan(textBuffer.CurrentSnapshot);
                        var text = textBuffer.CurrentSnapshot.GetText(span);

                        if (!whitespaceRegex.IsMatch(text)) return;
                        textBuffer.Replace(span, whitespaceRegex.Replace(text, ""));
                    }));
            #endif

            textView.Closed += (sender, e) => {
                disp.Dispose();
                _openTextViewList.Remove(textView);
            };
        }
开发者ID:hmemcpy,项目名称:SaveAllTheTime,代码行数:75,代码来源:DocumentMonitorService.cs

示例15: CompositeDisposable_AddAfterDispose

        public void CompositeDisposable_AddAfterDispose()
        {
            var disp1 = false;
            var disp2 = false;

            var d1 = Disposable.Create(() => { disp1 = true; });
            var d2 = Disposable.Create(() => { disp2 = true; });
            var g = new CompositeDisposable(d1);
            Assert.AreEqual(1, g.Count);

            g.Dispose();
            Assert.IsTrue(disp1);
            Assert.AreEqual(0, g.Count); // CHECK

            g.Add(d2);
            Assert.IsTrue(disp2);
            Assert.AreEqual(0, g.Count); // CHECK

            Assert.IsTrue(g.IsDisposed);
        }
开发者ID:Ziriax,项目名称:Rx.NET,代码行数:20,代码来源:DisposableTests.cs


注:本文中的System.Linq.CompositeDisposable.Dispose方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。