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


C# IObservable.Synchronize方法代码示例

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


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

示例1: LineScroller

        public LineScroller(FileInfo file,
                IObservable<ILineProvider> latest,
                IObservable<ScrollRequest> scrollRequest,
                ILogger logger,
                IScheduler scheduler = null)
        {
            if (file == null) throw new ArgumentNullException(nameof(file));
            if (latest == null) throw new ArgumentNullException(nameof(latest));
            if (logger == null) throw new ArgumentNullException(nameof(logger));

            logger.Info($"Constructing file tailer for {file.FullName}");

            var lines = new SourceCache<Line, LineKey>(l=>l.Key);
            Lines = lines.AsObservableCache();

            var locker = new object();
            scrollRequest = scrollRequest.Synchronize(locker);


            var aggregator = latest.CombineLatest(scrollRequest, (currentLines, scroll) => currentLines.ReadLines(scroll).ToArray())
                .Subscribe(currentPage =>
                {
                    var previous = lines.Items.ToArray();
                    var added = currentPage.Except(previous,Line.TextStartComparer).ToArray();
                    var removed = previous.Except(currentPage, Line.TextStartComparer).ToArray();

                    lines.Edit(innerCache =>
                    {
                        if (removed.Any()) innerCache.Remove(removed);
                        if (added.Any()) innerCache.AddOrUpdate(added);
                    });
                });

            _cleanUp = new CompositeDisposable(Lines, lines, aggregator);
        }
开发者ID:abuzhynsky,项目名称:TailBlazer,代码行数:35,代码来源:LineScroller.cs

示例2: FileTailer

        public FileTailer(FileInfo file,
                IObservable<FileSearchResult> filter,
                IObservable<ScrollRequest> scrollRequest,
                ILogger logger,
                IScheduler scheduler = null)
        {
            if (file == null) throw new ArgumentNullException(nameof(file));
            if (filter == null) throw new ArgumentNullException(nameof(filter));
            if (logger == null) throw new ArgumentNullException(nameof(logger));

            logger.Info($"Constructing file tailer for {file.FullName}");

            var lines = new SourceList<Line>();
            Lines = lines.AsObservableList();

            var isBusy = new Subject<bool>();
            IsSearching = isBusy.AsObservable();

            var locker = new object();
            scrollRequest = scrollRequest.Synchronize(locker);

            var fileWatcher = file.WatchFile(scheduler: scheduler)
                            .DistinctUntilChanged()
                            .TakeWhile(notification => notification.Exists).Repeat()
                            .Replay(1).RefCount();

            var indexer = fileWatcher.Index().Replay(1).RefCount();

            //compare latest lines and latest filter and only take the filtered results it is not empty
            var latestLines = indexer.Cast<ILineProvider>().Synchronize(locker);
            var latestFilter = filter.Cast<ILineProvider>().Synchronize(locker);
            var latest = latestLines.CombineLatest(latestFilter, (l, f) => f.IsEmpty ? l : f);

            MatchedLines = latest.Select(provider => provider.Count);
            TotalLines = latestLines.Select(x => x.Count);
            FileSize = fileWatcher.Select(notification => notification.Size);
            IsLoading = indexer.Take(1).Select(_ => false).StartWith(true);

            var aggregator = latest.CombineLatest(scrollRequest, (currentLines, scroll) =>
            {
                return currentLines.ReadLines(scroll).ToArray();
            })
            .Subscribe(currentPage =>
            {
                var previous = lines.Items.ToArray();
                var added = currentPage.Except(previous).ToArray();
                var removed = previous.Except(currentPage).ToArray();

                lines.Edit(innerList =>
                {
                    if (removed.Any()) innerList.RemoveMany(removed);
                    if (added.Any()) innerList.AddRange(added);
                });

            });

            //var aggregator = latest.CombineLatest(scrollRequest, (currentLines, scroll) =>
            //{
            //    //TODO: Read entire page, the check which lines should be added and which shold be removed
            //    //as part of that work, get the maximum inded [this is the head!]

            //    //   Debug.WriteLine($"{scroll.Mode}, {scroll.FirstIndex}, {scroll.PageSize}");

            //    var currentPage = currentLines.GetIndicies(scroll).ToArray();

            //    var previous = lines.Items.Select(l => l.LineInfo).ToArray();
            //    var removed = previous.Except(currentPage, LineInfo.LineIndexComparer).ToArray();
            //    var added = currentPage.Except(previous, LineInfo.LineIndexComparer).ToArray();
            //    //calculated added and removed lines
            //    var removedLines = lines.Items.Where(l => removed.Contains(l.LineInfo)).ToArray();

            //    Func<long, DateTime?> isTail = l =>
            //    {
            //        //account for time with tail (i.e. add time to ILineProvider.TailStartsAt )
            //        var tail = currentLines.TailStartsAt;
            //        var onTail = tail != -1 && l >= tail;
            //        return onTail ? DateTime.Now : (DateTime?)null;
            //    };

            //    //Console.WriteLine();
            //    //finally we can load the line from the file todo: Add encdoing back in
            //    var newLines = file.ReadLine(added, (lineIndex, text, position) => new Line(lineIndex, text, isTail(position)), Encoding.UTF8).ToArray();

            //    return new { NewLines = newLines, OldLines = removedLines };
            //})
            //.Where(fn => fn.NewLines.Length + fn.OldLines.Length > 0)
            //.Subscribe(changes =>
            //{
            //    //update observable list
            //    lines.Edit(innerList =>
            //{
            //    if (changes.OldLines.Any()) innerList.RemoveMany(changes.OldLines);
            //    if (changes.NewLines.Any()) innerList.AddRange(changes.NewLines);
            //});
            //});

            _cleanUp = new CompositeDisposable(Lines, lines, aggregator, Disposable.Create(() => isBusy.OnCompleted()));
        }
开发者ID:ivanatpr,项目名称:TailBlazer,代码行数:98,代码来源:FileTailer.cs

示例3: FileTailer

        public FileTailer(FileInfo file, 
            IObservable<string> textToMatch,
            IObservable<ScrollRequest> scrollRequest,
            IScheduler scheduler=null)
        {
            if (file == null) throw new ArgumentNullException(nameof(file));
            if (textToMatch == null) throw new ArgumentNullException(nameof(textToMatch));

            var lines = new SourceList<Line>();
            Lines = lines.AsObservableList();

            var locker = new object();
            scrollRequest = scrollRequest.Synchronize(locker);

            var metronome = Observable
                    .Interval(TimeSpan.FromMilliseconds(250), scheduler ?? Scheduler.Default)
                    .ToUnit()
                    .Replay().RefCount();

            //temp mess for a few days
            var indexer = file.WatchFile(metronome)
                            .TakeWhile(notification => notification.Exists)
                            .Repeat()
                            .Index()
                            .Synchronize(locker)
                            .Replay(1).RefCount();

            var matcher = textToMatch.Select(searchText =>
            {
                if (string.IsNullOrEmpty(searchText) || searchText.Length < 3)
                    return Observable.Return(LineMatches.None);

                return file.WatchFile(metronome)
                    .TakeWhile(notification => notification.Exists)
                    .Repeat()
                    .Match(s => s.Contains(searchText, StringComparison.OrdinalIgnoreCase));

            }).Switch()
            .Synchronize(locker)
            .Replay(1).RefCount();

            //count matching lines (all if no filter is specified)
            MatchedLines = indexer.CombineLatest(matcher, (indicies, matches) => matches == LineMatches.None ? indicies.Count : matches.Count);

            //count total line
            TotalLines = indexer.Select(x => x.Count);

            FileSize = file.WatchFile(metronome).Select(notification => notification.Size);

            var aggregator = indexer.CombineLatest(matcher, scrollRequest,(idx, mtch, scroll) => new CombinedResult(scroll, mtch, idx))
                .Select(result =>
                {
                    var scroll = result.Scroll;
                    var indicies = result.Incidies;
                    var matched = result.MatchedLines;

                    IEnumerable<LineIndex> indices;
                    if (result.MatchedLines.ChangedReason == LineMatchChangedReason.None)
                    {
                        indices = scroll.Mode == ScrollingMode.Tail
                            ? indicies.GetTail(scroll)
                            : indicies.GetFromIndex(scroll);
                    }
                    else
                    {
                        indices = scroll.Mode == ScrollingMode.Tail
                            ? indicies.GetTail(scroll, matched)
                            : indicies.GetFromIndex(scroll, matched);
                    }

                    var currentPage = indices.ToArray();
                    var previous = lines.Items.Select(l => l.LineIndex).ToArray();
                    var removed = previous.Except(currentPage).ToArray();
                    var removedLines = lines.Items.Where(l=> removed.Contains(l.LineIndex)).ToArray();

                    var added = currentPage.Except(previous).ToArray();
                    //finally we can load the line from the file
                    var newLines =  file.ReadLines(added, (lineIndex, text) =>
                    {
                        var isEndOfTail = indicies.ChangedReason != LinesChangedReason.Loaded && lineIndex.Line > indicies.TailStartsAt;

                        return new Line(lineIndex, text, isEndOfTail ? DateTime.Now : (DateTime?) null);
                    }, indicies.Encoding).ToArray();

                    return new { NewLines = newLines, OldLines = removedLines };
                })
                .RetryWithBackOff((Exception error, int attempts) =>
                {
                    //todo: plug in file missing or error into the screen
                    return TimeSpan.FromSeconds(1);
                 })
                 .Where(fn=> fn.NewLines.Length + fn.OldLines.Length > 0)
                .Subscribe(changes =>
                {
                    //update observable list
                    lines.Edit(innerList =>
                    {
                        if (changes.OldLines.Any()) innerList.RemoveMany(changes.OldLines);
                        if (changes.NewLines.Any())  innerList.AddRange(changes.NewLines);
                    });
//.........这里部分代码省略.........
开发者ID:bestpetrovich,项目名称:TailBlazer,代码行数:101,代码来源:FileTailer.cs

示例4: Add

 public IDisposable Add(IObservable<string> source)
 {
     return source
         .Synchronize(this)
         .Subscribe(line => _file.WriteLine(line));
 }
开发者ID:filmackay,项目名称:live,代码行数:6,代码来源:TraceFile.cs

示例5: FileTailer

        public FileTailer(FileInfo file, 
            IObservable<string> textToMatch,
            IObservable<ScrollRequest> scrollRequest,
            IScheduler scheduler=null)
        {
            if (file == null) throw new ArgumentNullException(nameof(file));
            if (textToMatch == null) throw new ArgumentNullException(nameof(textToMatch));

            var lines = new SourceList<Line>();
            Lines = lines.AsObservableList();

            var matcher = textToMatch.Select(searchText =>
            {
                if (string.IsNullOrEmpty(searchText) || searchText.Length < 3)
                    return Observable.Return(LineMatches.None);

                return file.WatchFile(scheduler: scheduler)
                    .TakeWhile(notification => notification.Exists)
                    .Repeat()
                    .Match(s => s.Contains(searchText, StringComparison.OrdinalIgnoreCase));

            }).Switch()
            .Replay(1).RefCount();

            //temp mess for a few days
            var indexer = file.WatchFile(scheduler: scheduler)
                                .TakeWhile(notification => notification.Exists)
                                .Repeat()
                                .Index()
                                .Replay(1).RefCount();

            //count matching lines (all if no filter is specified)
            MatchedLines = indexer.CombineLatest(matcher, (indicies, matches) => matches == LineMatches.None ? indicies.Count : matches.Count);

            //count total line
            TotalLines = indexer.Select(x => x.Count);

            //todo: plug in file missing or error into the screen

            var locker = new object();
            var theBeast = indexer.Synchronize(locker)
                .CombineLatest(matcher.Synchronize(locker), scrollRequest.Synchronize(locker),(idx, mtch, scroll) => new CombinedResult(scroll, mtch, idx))
                .Select(result =>
                {
                    var scroll = result.Scroll;
                    var allLines = result.Incidies;
                    var matched = result.MatchedLines;

                    IEnumerable<LineIndex> indices;
                    if (result.MatchedLines.ChangedReason == LineMatchChangedReason.None)
                    {
                        indices = scroll.Mode == ScrollingMode.Tail
                            ? allLines.GetTail(scroll)
                            : allLines.GetFromIndex(scroll);
                    }
                    else
                    {
                        indices = scroll.Mode == ScrollingMode.Tail
                            ? allLines.GetTail(scroll, matched)
                            : allLines.GetFromIndex(scroll, matched);
                    }

                    return  file.ReadLines(indices, (lineIndex, text) =>
                    {
                        var isEndOfTail = allLines.ChangedReason != LinesChangedReason.Loaded && lineIndex.Line > allLines.TailStartsAt;
                        return new Line(lineIndex.Line, lineIndex.Index, text,isEndOfTail ? DateTime.Now : (DateTime?) null);
                    }).ToArray();
                })
                //.RetryWithBackOff((error, attempts) =>
                //{
                //    //TODO: Log
                //    return TimeSpan.FromSeconds(1);
                //})
                .Subscribe(newPage =>
                {
                    //update observable list
                    lines.Edit(innerList =>
                    {

                        var removed = innerList.Except(newPage).ToArray();
                        var added = newPage.Except(innerList).ToArray();

                        if (removed.Any()) innerList.RemoveMany(removed);
                        if (added.Any())  innerList.AddRange(added);
                    });

                });

            ////this is the beast! Dynamically combine lines requested by the consumer
            ////with the lines which exist in the file. This enables proper virtualisation of the file
            //var scroller = matchedLines
            //    .CombineLatest(scrollRequest, (scanResult, request) => new {scanResult , request })
            //    .Subscribe(x =>
            //    {
            //        var mode = x.request.Mode;
            //        var pageSize = x.request.PageSize;
            //        var endOfTail = x.scanResult.EndOfTail;
            //        var isInitial = x.scanResult.Index==0;
            //        var allLines = x.scanResult.MatchingLines;
            //        var previousPage = lines.Items.Select(l => new LineIndex(l.Number, l.Index, 0, 0)).ToArray();
//.........这里部分代码省略.........
开发者ID:WELL-E,项目名称:TailBlazer,代码行数:101,代码来源:FileTailer.cs


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