C# 多线程 08-使用 Reactive Extensions 02-编写自定义的可观察对象
🏷️ 《C# 多线程》
示例代码
csharp
/// <summary>
/// 编写自定义的可观察对象
/// </summary>
/// <param name="args"></param>
static void Main(string[] args)
{
var observer = new CustomObserver();
var goodObservable = new CustomSequence(new[] { 1, 2, 3, 4, 5 });
var badObservable = new CustomSequence(null);
// 同步订阅
using (IDisposable subscription = goodObservable.Subscribe(observer))
{
}
// 异步订阅
using (IDisposable subscription = goodObservable.SubscribeOn(TaskPoolScheduler.Default).Subscribe(observer))
{
// 延迟一段时间等待异步任务完成
Thread.Sleep(TimeSpan.FromMilliseconds(100));
Console.WriteLine("Press Enter to continue");
Console.ReadLine();
}
// 异步订阅异常时
using (IDisposable subscription = badObservable.SubscribeOn(TaskPoolScheduler.Default).Subscribe(observer))
{
// 延迟一段时间等待异步任务完成
Thread.Sleep(TimeSpan.FromMilliseconds(100));
Console.WriteLine("Press Enter to continue");
Console.ReadLine();
}
}
/// <summary>
/// 自定义观察者
/// </summary>
class CustomObserver : IObserver<int>
{
public void OnCompleted()
{
Console.WriteLine("Completed");
}
public void OnError(Exception error)
{
Console.WriteLine($"Error: {error.Message}");
}
public void OnNext(int value)
{
Console.WriteLine($"Next value: {value}; Thread id: {Thread.CurrentThread.ManagedThreadId}");
}
}
/// <summary>
/// 自定义可观察对象
/// </summary>
class CustomSequence : IObservable<int>
{
private readonly IEnumerable<int> _numbers;
public CustomSequence(IEnumerable<int> numbers)
{
_numbers = numbers;
}
public IDisposable Subscribe(IObserver<int> observer)
{
foreach (var number in _numbers)
{
observer.OnNext(number);
}
observer.OnCompleted();
return Disposable.Empty;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
运行结果
txt
Next value: 1; Thread id: 1
Next value: 2; Thread id: 1
Next value: 3; Thread id: 1
Next value: 4; Thread id: 1
Next value: 5; Thread id: 1
Completed
Next value: 1; Thread id: 4
Next value: 2; Thread id: 4
Next value: 3; Thread id: 4
Next value: 4; Thread id: 4
Next value: 5; Thread id: 4
Completed
Press Enter to continue
Error: 未将对象引用设置到对象的实例。
Press Enter to continue
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16