如何使用Rx.NET接收回调?

时间:2018-12-31 14:29:37

标签: c# system.reactive rx.net

假设我有3个学生证。

我想做的事情:

  1. 异步获取3名学生的信息。
  2. 如果回调未在4秒钟内出现,它将对该网络呼叫重试3次。

    这是我的代码:

    Dictionary<string, SemaphoreSlim> semaphoreSlims = new Dictionary<string, 
    SemaphoreSlim>  
    {
        { "1", new SemaphoreSlim(0, 1) },
        { "2", new SemaphoreSlim(0, 1) },
        { "3", new SemaphoreSlim(0, 1) }
    };
    
    IObservable<string> studentIds = new string[] {"1", "2", "3"}.ToObservable();
    
    private IObservable<Student> LoadStudent(string id) {
        return Observable.Create<Student>(
            async o =>
            {
                StudentFoundDelegate studentDetailHandler = (Student student) =>
                {
                     // callback found
                     semaphoreSlims[id].Release();
                     o.OnNext(student);
                };
    
                StudentNotFoundDelegate errorHandler = (string representation, Result eCode) =>
                {
                     // callback found
                    semaphoreSlims[id].Release();
                    o.OnError(new Exception("Student Not Found"));
                };
    
                // Api calls
                StudentManager.Instance.GetStudentDetail(id, studentDetailHandler, errorHandler);
    
                await semaphoreSlims[id].WaitAsync();
    
                return Disposable.Empty;
            });
     }
    
     Observable.Timeout(studentIds.SelectMany(id => LoadStudent(id)), TimeSpan.FromMilliseconds(4000))
             .SubscribeOn(ThreadPoolScheduler.Default)
             .Retry(3)
             .Subscribe(
                student =>
                {
                    Logger.LogMessage("Found Student "+ student);
                },
    
                (ex) =>
                {
                    Logger.LogMessage(ex + "");
                }
     );
    

但是,我没有收到任何回调。任何人都可以建议我在哪里做错了,正确的解决方法是什么。谢谢。

0 个答案:

没有答案