مدیریت همزمانی و طول عمر توالیهای Reactive extensions در یک برنامهی دسکتاپ
نویسنده: وحید نصیری
تاریخ: ۱۳۹۳/۰۲/۲۹ ۷:۵
آدرس: www.dntips.ir
| مطالب | ۳۶۹۴ |
| نویسندگان | ۲۷۶ |
| گروههای مطالب | ۱۰۲۴ |
| نقشههای راه | ۱۱۹ |
| دورهها | ۱۴ |
| اشتراکها | ۱۷۹۱۴ |
PM> Install-Package Rx-Main PM> Install-Package Rx-WPF
private static IEnumerable<string> readFile(string filename)
{
using (TextReader reader = File.OpenText(filename))
{
string line;
while ((line = reader.ReadLine()) != null)
{
Thread.Sleep(100);
yield return line;
}
}
} <Window x:Class="WpfApplicationRxTests.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="450" Width="525">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="*" />
<RowDefinition Height="Auto" />
</Grid.RowDefinitions>
<Button Grid.Row="0" Name="btnGenerateSequence" Click="btnGenerateSequence_Click">Generate sequence</Button>
<ListBox Grid.Row="1" Name="lstNumbers" />
<Button Grid.Row="2" IsEnabled="False" Name="btnStop" Click="btnStop_Click">Stop</Button>
</Grid>
</Window> using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.IO;
using System.Reactive.Concurrency;
using System.Reactive.Linq;
using System.Threading;
using System.Windows;
namespace WpfApplicationRxTests
{
public partial class MainWindow
{
public MainWindow()
{
InitializeComponent();
}
private static IEnumerable<string> readFile(string filename)
{
using (TextReader reader = File.OpenText(filename))
{
string line;
while ((line = reader.ReadLine()) != null)
{
Thread.Sleep(100);
yield return line;
}
}
}
private IDisposable _subscribe;
private void btnGenerateSequence_Click(object sender, RoutedEventArgs e)
{
btnGenerateSequence.IsEnabled = false;
btnStop.IsEnabled = true;
var items = new ObservableCollection<string>();
lstNumbers.ItemsSource = items;
_subscribe = readFile("test.txt").ToObservable()
.SubscribeOn(ThreadPoolScheduler.Instance)
.ObserveOn(DispatcherScheduler.Current)
.Finally(finallyAction: () =>
{
btnGenerateSequence.IsEnabled = true;
btnStop.IsEnabled = false;
})
.Subscribe(onNext: line =>
{
items.Add(line);
},
onError: ex => { },
onCompleted: () =>
{
//lstNumbers.ItemsSource = items;
});
}
private void btnStop_Click(object sender, RoutedEventArgs e)
{
_subscribe.Dispose();
}
}
}