Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.Collections.Generic;
- using System.Collections.ObjectModel;
- using System.ComponentModel;
- using System.Linq;
- using System.Runtime.CompilerServices;
- using System.Threading;
- namespace LoopingEnumerable
- {
- class Program
- {
- static void Main(string[] args)
- {
- Console.WriteLine("Starting Loop");
- var collection = new ObservableCollection<Translation>
- {
- new Translation(),
- new Translation(),
- new Translation(),
- new Translation(),
- new Translation(),
- new Translation(),
- new Translation(),
- new Translation(),
- new Translation(),
- new Translation(),
- };
- var source = collection.Where(x => string.IsNullOrEmpty(x.TranslatedText));
- var count = source.Count();
- Console.WriteLine($"Count : {count}");
- var token = new CancellationToken();
- var progress = new Progress<int>(i => Console.WriteLine(i));
- Console.WriteLine("Starting Loop");
- Loop_For(source, token, progress);
- //Loop_ForEach(source, token, progress);
- Console.WriteLine("Finished Loop");
- Console.ReadKey();
- }
- public static void Loop_For(IEnumerable<Translation> items, CancellationToken cancellationToken, IProgress<int> progress)
- {
- for (int i = 0; i < items.Count(); i++)
- {
- if (cancellationToken.IsCancellationRequested)
- {
- return;
- }
- var obj = items.ElementAt(i);
- obj.TranslatedText = "something";
- progress.Report(i + 1);
- Thread.Sleep(200);
- }
- }
- public static void Loop_ForEach(IEnumerable<Translation> items, CancellationToken cancellationToken, IProgress<int> progress)
- {
- int count = 0;
- foreach (var item in items)
- {
- if (cancellationToken.IsCancellationRequested)
- {
- return;
- }
- item.TranslatedText = "something";
- progress.Report(++count);
- Thread.Sleep(200);
- }
- }
- }
- public class Translation : BindableBase
- {
- public string Key { get; set; }
- public string EnglishText { get; set; } = "Hello World";
- private string translatedText;
- public string TranslatedText
- {
- get { return translatedText; }
- set { SetProperty(ref translatedText, value); }
- }
- }
- public class BindableBase : INotifyPropertyChanged
- {
- public event PropertyChangedEventHandler PropertyChanged;
- protected void RaisePropertyChanged([CallerMemberName] string property = "")
- => PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(property));
- protected bool SetProperty<T>(ref T storage, T value, [CallerMemberName] string property = "")
- {
- if(EqualityComparer<T>.Default.Equals(storage, value) == false)
- {
- storage = value;
- RaisePropertyChanged(property);
- return true;
- }
- return false;
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement