gpt4 book ai didi

c# - 我如何查看我的响应式扩展查询在做什么?

转载 作者:IT王子 更新时间:2023-10-29 04:52:52 27 4
gpt4 key购买 nike

我正在编写一个包含大量运算符的复杂 Reactive Extensions 查询。我怎样才能看到发生了什么?

我会问和回答这个问题,因为它出现得相当多,而且可能具有很好的一般用途。

最佳答案

您可以在开发 Rx 运算符时随意将此函数附加到它们以查看发生了什么:

    public static IObservable<T> Spy<T>(this IObservable<T> source, string opName = null)
{
opName = opName ?? "IObservable";
Console.WriteLine("{0}: Observable obtained on Thread: {1}",
opName,
Thread.CurrentThread.ManagedThreadId);

return Observable.Create<T>(obs =>
{
Console.WriteLine("{0}: Subscribed to on Thread: {1}",
opName,
Thread.CurrentThread.ManagedThreadId);

try
{
var subscription = source
.Do(x => Console.WriteLine("{0}: OnNext({1}) on Thread: {2}",
opName,
x,
Thread.CurrentThread.ManagedThreadId),
ex => Console.WriteLine("{0}: OnError({1}) on Thread: {2}",
opName,
ex,
Thread.CurrentThread.ManagedThreadId),
() => Console.WriteLine("{0}: OnCompleted() on Thread: {1}",
opName,
Thread.CurrentThread.ManagedThreadId)
)
.Subscribe(obs);
return new CompositeDisposable(
subscription,
Disposable.Create(() => Console.WriteLine(
"{0}: Cleaned up on Thread: {1}",
opName,
Thread.CurrentThread.ManagedThreadId)));
}
finally
{
Console.WriteLine("{0}: Subscription completed.", opName);
}
});
}

这是一个示例用法,显示了 Range 的细微行为差异:

Observable.Range(0, 1).Spy("Range").Subscribe();

给出输出:

Range: Observable obtained on Thread: 7
Range: Subscribed to on Thread: 7
Range: Subscription completed.
Range: OnNext(0) on Thread: 7
Range: OnCompleted() on Thread: 7
Range: Cleaned up on Thread: 7

但是这个:

Observable.Range(0, 1, Scheduler.Immediate).Spy("Range").Subscribe();

给出输出:

Range: Observable obtained on Thread: 7
Range: Subscribed to on Thread: 7
Range: OnNext(0) on Thread: 7
Range: OnCompleted() on Thread: 7
Range: Subscription completed.
Range: Cleaned up on Thread: 7

找出不同之处?

显然,您可以更改它以写入日志或调试,或使用预处理器指令在发布版本等上执行精益传递订阅...

您可以在整个运算符链中应用Spy。例如:

Observable.Range(0,3).Spy("Range")
.Scan((acc, i) => acc + i).Spy("Scan").Subscribe();

给出输出:

Range: Observable obtained on Thread: 7
Scan: Observable obtained on Thread: 7
Scan: Subscribed to on Thread: 7
Range: Subscribed to on Thread: 7
Range: Subscription completed.
Scan: Subscription completed.
Range: OnNext(1) on Thread: 7
Scan: OnNext(1) on Thread: 7
Range: OnNext(2) on Thread: 7
Scan: OnNext(3) on Thread: 7
Range: OnCompleted() on Thread: 7
Scan: OnCompleted() on Thread: 7
Range: Cleaned up on Thread: 7
Scan: Cleaned up on Thread: 7

我相信您可以找到丰富它的方法以满足您的目的。

关于c# - 我如何查看我的响应式扩展查询在做什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20220755/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com