public void ContainsIsThreadSafe() { var test = new ConcurrentObservableCollection <int>(Concurrent) { 1, 2, 3 }; var task1 = Task.Run(() => { for (var i = 0; i < 10; i++) { test.Contains(2); Task.Delay(DelayTime).Wait(); test.Contains(4); } }); var task2 = Task.Run(() => { for (var i = 0; i < 10; i++) { test.Add(4); Task.Delay(DelayTime).Wait(); test.Add(5); } }); Task.WaitAll(task1, task2); }
public void WriteAndRead_ConcurrentReadAndWrite_SuccessfullyWritesElementsToCollection() { var array = new int[50]; for (int i = 0; i < 50; i++) { array[i] = i; } var col = new ConcurrentObservableCollection <int>(array); var task1 = new Task(() => { for (int i = 50; i < 100; i++) { col.Add(i); } }); int current = 0; var task2 = new Task(() => col.ForEach(c => { current = c; })); task1.Start(); task2.Start(); Task.WaitAll(new[] { task1, task2 }); Assert.That(col.Count, Is.EqualTo(100), "collection was not filled"); Assert.That(current, Is.InRange(49, 100), "enumeration was not running simultaneously with update"); #if NET45 Debug.Print("Collection size: {0}", col.Count); Debug.Print("current: {0}", current); #endif }
public void Read_ExceptionDuringEnumeration_LockReleased() { var array = new int[100]; for (int i = 0; i < 100; i++) { array[i] = i; } var col = new ConcurrentObservableCollection <int>(array); try { int x = 0; col.ForEach(c => { if (x++ > 50) { throw new Exception(); } }); } catch (Exception) { Console.WriteLine("Exception was fired"); } col.Add(3); Assert.That(col.Count, Is.EqualTo(101)); }
public void Write_AddElement_ElementAdded() { var col = new ConcurrentObservableCollection <string>(); col.Add("a"); Assert.That(col.First(), Is.EqualTo("a")); }
public void Performance_MonitorNumberOfAllocatedThreads() { int maxNumberOfThreads = 0; int currentNumberOfThreads = Process.GetCurrentProcess().Threads.Count; _testOutputHelper.WriteLine("Number of threads before run {0}", currentNumberOfThreads); for (int j = 0; j < 100; j++) { var threadSafe = new ConcurrentObservableCollection <int>(); for (int i = 0; i < 100; i++) { threadSafe.Add(i); if (i % 10 == 0) { int tmp = Process.GetCurrentProcess().Threads.Count; if (tmp > maxNumberOfThreads) { maxNumberOfThreads = tmp; } } } } _testOutputHelper.WriteLine("Max number of threads {0}", maxNumberOfThreads); (maxNumberOfThreads - currentNumberOfThreads).Should() .BeLessThan(10, "the number of threads should be low"); }
public async Task WriteInConcurrentObservableCollectionUIThread() { using (var collection = new ConcurrentObservableCollection <int>()) { _collectionChangedCount = 0; collection.CollectionChanged += Collection_CollectionChanged; await TaskHelper.RunOnUIThreadAsync(() => { for (int i = 1; i < 10000; i++) { for (int j = 1; j < 10; j++) { collection.Add(i *j); } collection.RemoveAt(collection.Count - 1); collection.Remove(i); collection.Move(0, 6); collection.Insert(0, i *i); } }).ConfigureAwait(false); Assert.AreEqual(79992, collection.Count); Assert.AreEqual(129987, _collectionChangedCount); } }
public async Task WriteInConcurrentObservableCollectionMultiThread() { using (var collection = new ConcurrentObservableCollection <string>()) using (var resetEvent = new ManualResetEvent(false)) { _collectionChangedCount = 0; collection.CollectionChanged += Collection_CollectionChanged; var tasks = new List <Task>(); for (int i = 0; i < 100; i++) { tasks.Add(Task.Run(() => { resetEvent.WaitOne(); for (int j = 0; j < 10000; j++) { collection.Add(i.ToString(CultureInfo.InvariantCulture) + " - " + j.ToString(CultureInfo.InvariantCulture)); } })); } resetEvent.Set(); await Task.WhenAll(tasks).ConfigureAwait(false); int count = collection.Count; Assert.AreEqual(1000000, count); Assert.AreEqual(1000000, _collectionChangedCount); } }
public void WriteAndRead_ConcurrentReadAndWrite_SuccessfullyWritesElementsToCollection() { var array = new int[50]; for (int i = 0; i < 50; i++) { array[i] = i; } var col = new ConcurrentObservableCollection <int>(array); var task1 = new Task(() => { for (int i = 50; i < 100; i++) { col.Add(i); } }); int current = 0; var task2 = new Task(() => col.ForEach(c => { current = c; })); task1.Start(); task2.Start(); Task.WaitAll(task1, task2); col.Count.Should().Be(100, "the collection should be populated properly"); current.Should().BeInRange(49, 100, " the enumeration should have run in-sync with the update"); }
public void Read_ExceptionDuringEnumeration_LockReleased() { var array = new int[100]; for (int i = 0; i < 100; i++) { array[i] = i; } var col = new ConcurrentObservableCollection <int>(array); try { int x = 0; col.ForEach(c => { if (x++ > 50) { throw new Exception(); } }); } catch (Exception) { _testOutputHelper.WriteLine("Exception was fired"); } col.Add(3); col.Count.Should().Be(101); }
private void InitObservers() { var deletedRows = new ConcurrentObservableCollection<ApplicationViewModel>(); deletedRows.ToObservableRx<ApplicationViewModel>().ObserveOnDispatcher().Subscribe((appVm) => { ApplicationQueue.Remove(appVm); }); _deleteAppObserver = Observer.Create<ApplicationViewModel>((item) => { var model = item.GetModel(); if (item.State != AppState.ToDelete) { return; } item.State = AppState.Deleting; try { _applicationManager.DeleteApp(model); deletedRows.Add(item); } catch (Exception ex) { item.State = AppState.DeleteError; item.ErrorMsg = ex.ToString(); } }); this.ObserveProperty("SearchText") .Throttle(TimeSpan.FromMilliseconds(500)) .Select(args => SearchText) .DistinctUntilChanged() .ObserveOnDispatcher() .Subscribe(Observer.Create((string text) => UpdateAppList())); }
public void Performance_MonitorNumberOfAllocatedThreads() { int maxNumberOfThreads = 0; int currentNumberOfThreads = Process.GetCurrentProcess().Threads.Count; Console.WriteLine("Number of threads before run {0}", currentNumberOfThreads); for (int j = 0; j < 100; j++) { var threadSafe = new ConcurrentObservableCollection <int>(); for (int i = 0; i < 100; i++) { threadSafe.Add(i); if (i % 10 == 0) { int tmp = Process.GetCurrentProcess().Threads.Count; if (tmp > maxNumberOfThreads) { maxNumberOfThreads = tmp; } } } } Console.WriteLine("Max number of threads {0}", maxNumberOfThreads); Assert.That(maxNumberOfThreads - currentNumberOfThreads, Is.LessThan(10), "too many threads created"); }
public void Write_ConcurrentWrite_SuccessfullyWritesElementsToCollection() { var col = new ConcurrentObservableCollection <int>(); var task1 = new Task(() => { for (int i = 0; i < 1000; i++) { col.Add(i); Thread.Sleep(1); } }); var task2 = new Task(() => { for (int i = 0; i < 1000; i++) { col.Clear(); Thread.Sleep(1); } }); task1.Start(); task2.Start(); Task.WaitAll(task1, task2); col.Count.Should().BeLessThan(1000); }
public void Write_ConcurrentWrite_SuccessfullyWritesElementsToCollection() { var col = new ConcurrentObservableCollection <int>(); var task1 = new Task(() => { for (int i = 0; i < 1000; i++) { col.Add(i); Thread.Sleep(1); } }); var task2 = new Task(() => { for (int i = 0; i < 1000; i++) { col.Clear(); Thread.Sleep(1); } }); task1.Start(); task2.Start(); Task.WaitAll(new[] { task1, task2 }); Assert.That(col.Count, Is.LessThan(1000)); #if NET45 Debug.Print("Collection size: {0}", col.Count); #endif }
public void CopyToIsThreadSafe() { var test = new ConcurrentObservableCollection <int>(Concurrent) { 1, 2, 3 }; var out1 = new int[5]; var out2 = new int[5]; var task1 = Task.Run(() => { for (var i = 0; i < 10; i++) { test.CopyTo(out1, 0); Task.Delay(DelayTime).Wait(); test.CopyTo(out2, 0); } }); var task2 = Task.Run(() => { for (var i = 0; i < 10; i++) { test.Add(4); Task.Delay(DelayTime).Wait(); test.Remove(4); } }); Task.WaitAll(task1, task2); }
public void Read_CheckLengthAfterAdd_LengthIsUpdated() { var col = new ConcurrentObservableCollection <int>(); col.Add(1); col.Count.Should().Be(1); }
public void Write_AddElement_ElementAdded() { var col = new ConcurrentObservableCollection <string>(); col.Add("a"); col.First().Should().Be("a"); }
public void Read_CheckLengthAfterAdd_LengthIsUpdated() { var col = new ConcurrentObservableCollection <int>(); col.Add(1); Assert.That(col.Count, Is.EqualTo(1)); }
public void Write_ComplexOperation_CollectionUpdatedProperly() { var col = new ConcurrentObservableCollection <string>(new[] { "a", "b", "c" }); col.Add("d"); col.Remove("b"); col.Insert(0, "x"); col.AddRange(new[] { "z", "f", "y" }); col.RemoveAt(4); col.RemoveRange(new[] { "y", "c" }); col[2] = "p"; CollectionAssert.AreEquivalent(new[] { "x", "a", "p", "f" }, col); }
public void Write_ComplexUpdateOperationFrom2ThreadsAndEnumerationInTheMiddle_CollectionUpdatedProperly() { var array = new int[100]; for (int i = 0; i < 100; i++) { array[i] = i; } var col = new ConcurrentObservableCollection <int>(array); var task1 = new Task(() => { for (int i = 100; i < 200; i++) { _testOutputHelper.WriteLine("Add {0}", i); col.Add(i); } }); var task2 = new Task(() => { for (int i = 0; i < 100; i++) { _testOutputHelper.WriteLine("Remove {0}", i); col.Remove(i); } }); var list = new List <int>(); var task3 = new Task(() => col.ForEach(c => { _testOutputHelper.WriteLine("Enumerating {0}", c); list.Add(c); })); task1.Start(); task2.Start(); task3.Start(); Task.WaitAll(task1, task2, task3); var expected = new int[100]; for (int i = 100; i < 200; i++) { expected[i - 100] = i; } col.Should().BeEquivalentTo(expected, "the collection should be updated properly"); list.Should().NotBeEmpty("the enumeration should find at least one element"); }
public void Write_ComplexUpdateOperationFrom2ThreadsAndEnumerationInTheMiddle_CollectionUpdatedProperly() { var array = new int[100]; for (int i = 0; i < 100; i++) { array[i] = i; } var col = new ConcurrentObservableCollection <int>(array); var task1 = new Task(() => { for (int i = 100; i < 200; i++) { Console.WriteLine("Add {0}", i); col.Add(i); } }); var task2 = new Task(() => { for (int i = 0; i < 100; i++) { Console.WriteLine("Remove {0}", i); col.Remove(i); } }); var list = new List <int>(); var task3 = new Task(() => col.ForEach(c => { Console.WriteLine("Enumerating {0}", c); list.Add(c); })); task1.Start(); task2.Start(); task3.Start(); Task.WaitAll(new[] { task1, task2, task3 }); var expected = new int[100]; for (int i = 100; i < 200; i++) { expected[i - 100] = i; } CollectionAssert.AreEquivalent(expected, col, "collection was not properly updated"); CollectionAssert.IsNotEmpty(list, "Enumeration didnt find any element"); }
public void Write_FiresAddEvent() { var col = new ConcurrentObservableCollection <string>(); string received = string.Empty; col.CollectionChanged += (sender, args) => { if (args.Action == NotifyCollectionChangedAction.Add) { received = args.NewItems.OfType <string>().First(); } }; col.Add("a"); Assert.That(received, Is.EqualTo("a")); }
public void AddIsThreadSafe() { var test = new ConcurrentObservableCollection <int> (Concurrent) { 1, 2, 3 }; var task1 = Task.Run(() => { foreach (var i in test) { Task.Delay(DelayTime).Wait(); } }); var task2 = Task.Run(() => { test.Add(4); Task.Delay(DelayTime).Wait(); test.Add(5); }); Task.WaitAll(task1, task2); }
public static Podcast FromRoamingData(IServiceContext serviceContext, RoamingPodcastData data) { Podcast podcast = new Podcast(serviceContext); podcast.Title = data.Title; podcast.PodcastUri = data.Uri; ConcurrentObservableCollection <Episode> episodes = new ConcurrentObservableCollection <Episode>(s_EpisodeOrdering, true); podcast.Episodes = episodes; foreach (RoamingEpisodeData episodeData in data.RoamingEpisodesData) { episodes.Add(Episode.FromRoamingData(serviceContext, podcast.FileName, episodeData)); } podcast.Episodes.HoldNotifications = false; return(podcast); }
public void TestConcurrentObservableCollectionOrdering() { ConcurrentObservableCollection <string> collection = new ConcurrentObservableCollection <string>(s => int.Parse(s)); for (int i = 0; i < 20; i++) { collection.Add(i.ToString()); } int j = 0; foreach (string s in collection) { Assert.AreEqual(j.ToString(), s); j++; } }
public void ConcurrentObservableCollectionSerializationTest() { var serializer = new BinaryFormatter(); var stream = new MemoryStream(); var collection = new ConcurrentObservableCollection <string>(); for (int i = 0; i < 10; i++) { collection.Add("TestItem" + (i + 1).ToString()); } serializer.Serialize(stream, collection); stream.Position = 0; collection = serializer.Deserialize(stream) as ConcurrentObservableCollection <string>; for (int i = 0; i < 10; i++) { Assert.AreEqual("TestItem" + (i + 1).ToString(), collection[i]); } }
public void Read_CheckContainsWhileAdding() { var col = new ConcurrentObservableCollection <int>(new[] { 1, 2, 3, 4, 5 }); var task1 = new Task(() => { for (int i = 10; i < 1000; i++) { col.Add(i); Thread.Sleep(1); } }); bool contains = false; var task2 = new Task(() => { contains = col.Contains(1); }); task1.Start(); Thread.Sleep(5); task2.Start(); Task.WaitAll(task1, task2); contains.Should().BeTrue(); }
public void Write_ComplexUpdateOperationFrom2Threads_CollectionUpdatedProperly() { var array = new int[100]; for (int i = 0; i < 100; i++) { array[i] = i; } var col = new ConcurrentObservableCollection <int>(array); var task1 = new Task(() => { for (int i = 100; i < 200; i++) { col.Add(i); } }); var task2 = new Task(() => { for (int i = 0; i < 100; i++) { col.Remove(i); } }); task1.Start(); task2.Start(); Task.WaitAll(task1, task2); var expected = new int[100]; for (int i = 100; i < 200; i++) { expected[i - 100] = i; } col.Should().BeEquivalentTo(expected); }
/// <summary> /// Initializes a new instance of the <see cref="PointsOfInterestPage"/> class. /// </summary> /// <param name="pointsOfInterest">Points of interest to display.</param> public PointsOfInterestPage(ConcurrentObservableCollection <PointOfInterest> pointsOfInterest) { Title = "Points of Interest"; ListView pointsOfInterestList = new ListView(ListViewCachingStrategy.RecycleElement); pointsOfInterestList.ItemTemplate = new DataTemplate(typeof(TextCell)); pointsOfInterestList.ItemTemplate.SetBinding(TextCell.TextProperty, new Binding(".", stringFormat: "{0}")); pointsOfInterestList.ItemsSource = pointsOfInterest; pointsOfInterestList.ItemTapped += async(o, e) => { if (pointsOfInterestList.SelectedItem == null) { return; } PointOfInterest selectedPointOfInterest = pointsOfInterestList.SelectedItem as PointOfInterest; string selectedAction = await DisplayActionSheet(selectedPointOfInterest.ToString(), "Cancel", null, "Delete"); if (selectedAction == "Delete") { if (await DisplayAlert("Delete " + selectedPointOfInterest.Name + "?", "This action cannot be undone.", "Delete", "Cancel")) { pointsOfInterest.Remove(selectedPointOfInterest); pointsOfInterestList.SelectedItem = null; // reset it manually, since it isn't done automatically. } } }; Content = pointsOfInterestList; CancellationTokenSource gpsCancellationTokenSource = null; ToolbarItems.Add(new ToolbarItem(null, "plus.png", async() => { List <Input> inputs = await SensusServiceHelper.Get().PromptForInputsAsync("Define Point Of Interest", new Input[] { new SingleLineTextInput("POI Name:", Keyboard.Text) { Required = false }, new SingleLineTextInput("POI Type:", Keyboard.Text) { Required = false }, new SingleLineTextInput("Address:", Keyboard.Text) { Required = false } }, null, true, null, null, null, null, false); if (inputs == null) { return; } string name = inputs[0].Value as string; string type = inputs[1].Value as string; string address = inputs[2].Value as string; if (string.IsNullOrWhiteSpace(name) && string.IsNullOrWhiteSpace(type)) { await SensusServiceHelper.Get().FlashNotificationAsync("You must enter either a name or type (or both)."); } else { Action <List <Position> > addPOI = new Action <List <Position> >(poiPositions => { SensusContext.Current.MainThreadSynchronizer.ExecuteThreadSafe(async() => { if (poiPositions != null && poiPositions.Count > 0 && await DisplayAlert("Add POI?", "Would you like to add " + poiPositions.Count + " point(s) of interest?", "Yes", "No")) { foreach (Position poiPosition in poiPositions) { pointsOfInterest.Add(new PointOfInterest(name, type, poiPosition.ToGeolocationPosition())); } } }); }); string newPinName = name + (string.IsNullOrWhiteSpace(type) ? "" : " (" + type + ")"); if (string.IsNullOrWhiteSpace(address)) { // cancel existing token source if we have one if (gpsCancellationTokenSource != null && !gpsCancellationTokenSource.IsCancellationRequested) { gpsCancellationTokenSource.Cancel(); } gpsCancellationTokenSource = new CancellationTokenSource(); Plugin.Geolocator.Abstractions.Position gpsPosition = await GpsReceiver.Get().GetReadingAsync(gpsCancellationTokenSource.Token, true); if (gpsPosition != null) { SensusServiceHelper.Get().GetPositionsFromMapAsync(gpsPosition.ToFormsPosition(), newPinName, addPOI); } } else { SensusServiceHelper.Get().GetPositionsFromMapAsync(address, newPinName, addPOI); } } })); Disappearing += (o, e) => { if (gpsCancellationTokenSource != null && !gpsCancellationTokenSource.IsCancellationRequested) { gpsCancellationTokenSource.Cancel(); } }; }
public void AddEpisode(Episode episode) { episode.PropertyChanged += OnEpisodePropertyChanged; Episodes.Add(episode); }
protected void Message(string message) { Messages.Add(message); }
public void ParseAction(string action, params string[] args) { Dictionary <string, string> data = ParseData(args); UIEvent e = new UIEvent(); switch (action) { case "NewAddressBook": if (data.ContainsKey("result")) { if (data.TryGetValue("result", out string val)) { if (val == "succeeded") { data.TryGetValue("name", out string name); e.SetAction(() => { MessageBox.Show($"Address book {name} successfully created."); e.MarkAsCompleted(); }); } else { e.SetAction(() => { MessageBox.Show("Failed to create new address book"); e.MarkAsCompleted(); }); } } } break; case "NewEntry": if (data.ContainsKey("result")) { if (data.TryGetValue("result", out string value)) { if (value == "succeeded") { data.TryGetValue("bn", out string bookName); data.TryGetValue("name", out string name); data.TryGetValue("surname", out string surname); data.TryGetValue("phone", out string phone); e.SetAction(() => { MainWindow.Instance.AddEntry(new AddressBookEntry() { Name = name, Surname = surname, PhoneNumber = phone }); e.MarkAsCompleted(); }); } } } break; case "BookList": if (data.TryGetValue("length", out string booksLengthString)) { List <string> bookNames = new List <string>(); if (int.TryParse(booksLengthString, out int length)) { for (int i = 0; i < length; i++) { data.TryGetValue("name" + i, out string book); bookNames.Add(book); } } e.SetAction(() => { new ChangeAddressBook(bookNames).Show(); e.MarkAsCompleted(); }); } break; case "ContactList": if (data.TryGetValue("length", out string lengthString)) { List <AddressBookEntry> entries = new List <AddressBookEntry>(); if (int.TryParse(lengthString, out int length)) { for (int i = 0; i < length; i++) { if (data.TryGetValue("index" + i, out string part)) { Dictionary <string, string> entryArgsDict = new Dictionary <string, string>(); foreach (string s in part.Split('|')) { string[] entryArgs = s.Split(':'); entryArgsDict.Add(entryArgs[0], entryArgs[1]); } entries.Add(new AddressBookEntry() { Name = entryArgsDict.GetData("name"), Surname = entryArgsDict.GetData("surname"), PhoneNumber = entryArgsDict.GetData("phone"), }); } } } e.SetAction(() => { MainWindow.Instance.SetData(entries); e.MarkAsCompleted(); }); } break; } UIEvents.Add(e); }