我想使用AsyncLocal通过异步工作流传递信息以进行跟踪。现在我遇到了RX的问题。
Thios是我的测试代码:
using System;
using System.Reactive.Linq;
using System.Reactive.Subjects;
using System.Threading;
using System.Threading.Tasks;
public class RxTest
{
private readonly Subject<int> test = new Subject<int>();
private readonly AsyncLocal<int> asyncContext = new AsyncLocal<int>();
public void Test()
{
this.test
// .ObserveOn(Scheduler.Default)
.Subscribe(this.OnNextNormal);
this.test
// .ObserveOn(Scheduler.Default)
.Delay(TimeSpan.FromMilliseconds(1))
.Subscribe(this.OnNextDelayed);
for (var i = 0; i < 2; i++)
{
var index = i;
Task.Run(() =>
{
this.asyncContext.Value = index;
Console.WriteLine(
$"Main\t\t{index} (Thread: {Thread.CurrentThread.ManagedThreadId}): AsyncLocal.Value => {this.asyncContext.Value}");
this.test.OnNext(index);
});
}
Console.ReadKey();
}
private void OnNextNormal(int obj)
{
Console.WriteLine(
$"OnNextNormal\t{obj} (Thread: {Thread.CurrentThread.ManagedThreadId}): AsyncLocal.Value => {this.asyncContext.Value}");
}
private void OnNextDelayed(int obj)
{
Console.WriteLine(
$"OnNextDelayed\t{obj} (Thread: {Thread.CurrentThread.ManagedThreadId}): AsyncLocal.Value => {this.asyncContext.Value}");
}
}
输出为:
Main 0(线程:5):AsyncLocal.Value => 0
Main 1(线程:6):AsyncLocal.Value => 1
OnNextNormal 0(线程:5):AsyncLocal.Value => 0
OnNextNormal 1(Thread:6):AsyncLocal.Value => 1
OnNextDelayed 0(线程:4):AsyncLocal.Value => 0
OnNextDelayed 1(线程:4):AsyncLocal.Value => 0
如您所见,AsyncLocal.Value不会流到延迟的订阅方法。
=> AsyncValue在延迟轨道上丢失
据我了解,普通的Subscribe()不使用调度程序,而Delay()使用调度程序。
当我对两个调用都使用ObserveOn()时,两者的输出如下
Main 0(线程:5):AsyncLocal.Value => 0
Main 1(线程:7):AsyncLocal.Value => 1
OnNextNormal 0(线程:9):AsyncLocal.Value => 0
OnNextNormal 1(线程:9):AsyncLocal.Value => 0
OnNextDelayed 0(线程:4):AsyncLocal.Value => 0
OnNextDelayed 1(线程:4):AsyncLocal.Value => 0
=> AsyncValue在每个轨道上丢失
有没有一种方法可以让ExecutionContext与RX一起使用?
我只找到this,但反过来这就是问题所在。他们解决了观察者上下文如何流动的问题。我想传达发布者的上下文。
我要实现的是:
预先感谢您的回答。
答案 0 :(得分:0)
Rx中的自由执行上下文使它适合大多数多线程方案。您可以通过绕开预定的方法来强制执行线程上下文,如下所示:
public static class Extensions
{
public static IObservable<T> TaskPoolDelay<T>(this IObservable<T> observable, TimeSpan delay)
{
return Observable.Create<T>(
observer => observable.Subscribe(
onNext: value => Task.Delay(delay).ContinueWith(_ => observer.OnNext(value)),
onError: observer.OnError,
onCompleted: observer.OnCompleted
)
);
}
}
输出:
OnNextDelayed 2 (Thread: 6): AsyncLocal.Value => 2
OnNextDelayed 3 (Thread: 10): AsyncLocal.Value => 3
OnNextDelayed 1 (Thread: 7): AsyncLocal.Value => 1
OnNextDelayed 0 (Thread: 5): AsyncLocal.Value => 0
这确实可以传递上下文,但是对于较大的查询,它很快变得复杂。我不确定实现在通知时保留上下文的IScheduler
是否能正常工作。如果消息复制没有太多的开销,那可能是最适合Rx的方式。