给定的可观察 A 表示传入请求...
interface IRequest
{
string Id { get; }
}
IObservable<IRequest> requests;
和表示响应的可观察 B ...
IObservable<string> responses;
我需要测量产生响应所需的时间。我当前的解决方案如下所示。这有效,但我不确定是否可以简化或更精简地实施。我还担心实际响应时间([GEN]
(和观察到的响应时间([OBS]
(之间的偏差,如果generatedResponseTime
设置为低于50ms,则偏差变得安静显着。
class Program
{
public class Request
{
public string Id { get; set; }
}
static void Main(string[] args)
{
var generatedResponseTime = 100;
var responseSub = new Subject<string>();
IObservable<Request> requests = Observable.Interval(TimeSpan.FromMilliseconds(1000))
.Select(x=> new Request { Id = x.ToString("d") });
IObservable<string> responses = responseSub.AsObservable();
var responseTime = requests
.Where(x => !string.IsNullOrEmpty(x.Id))
.Select(req => new { Id = req.Id, Start = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds() })
.SelectMany(req => responses
.Where(reqId => reqId == req.Id)
.Select(_ => new { RequestId = req.Id, ResponseTime = (int)(DateTimeOffset.UtcNow.ToUnixTimeMilliseconds() - req.Start) })
.Take(1))
.Publish()
.RefCount();
requests.ObserveOn(TaskPoolScheduler.Default)
.Subscribe(req =>
{
Console.WriteLine($"[GEN] {req.Id} = {generatedResponseTime} ms");
Thread.Sleep(generatedResponseTime);
responseSub.OnNext(req.Id);
});
responseTime.Subscribe(x => Console.WriteLine($"[OBS] {x.RequestId} = {x.ResponseTime} ms"));
Console.ReadLine();
}
}
下面是使用一些内置运算符的替代方法。解决方案中也没有多个订阅问题:
var responseTime2 = requests
.Timestamp()
.Join(responses.Timestamp(),
request => Observable.Never<Unit>(), //timeout criteria
response => Observable.Empty<Unit>(),
(request, response) => (request: request, response: response)
)
.Where(t => t.request.Value.Id == t.response.Value)
.Select(t => t.response.Timestamp.ToUnixTimeMilliseconds() - t.request.Timestamp.ToUnixTimeMilliseconds())
如果您对请求有任何超时条件,那么从性能角度来看,将其放在注释指示的位置会很有帮助。否则,Join/Where
组合的性能会随着时间的推移而恶化。