IHttpAsyncHandler和IObservable Web请求

时间:2010-04-07 22:37:41

标签: c# asp.net webrequest system.reactive ihttpasynchandler

在Async处理程序中我正在从webrequest创建一个IObservable,它返回一个重定向字符串。

我正在订阅那个observable并调用AsyncResult.CompleteCall()但是我被迫使用Thread.Sleep(100)来执行它。它每次都不起作用。我很确定这不正确。你能不能发光一下。谢谢!

    public IAsyncResult BeginProcessRequest(HttpContext context, AsyncCallback cb, object state)
    {
        _context = context;
        _ar = new AsyncResult(cb, state);

        _tweet = context.Request["tweet"];
        string url = context.Request["url"];

        if(String.IsNullOrEmpty(_tweet) || String.IsNullOrEmpty(url))
        {
            DisplayError("<h2>Tweet or url cannot be empty</h2>");
            return _ar;
        }

        _oAuth = new oAuthTwitterRx();
        using (_oAuth.AuthorizationLinkGet().Subscribe(p =>
        {
            _context.Response.Redirect(p);
            _ar.CompleteCall();
        },
                exception => DisplayError("<h2>Unable to connect to twitter, please try again</h2>")
                ))


        return _ar;
    }

public class AsyncResult : IAsyncResult
{
    private AsyncCallback _cb;
    private object _state;
    private ManualResetEvent _event;
    private bool _completed = false;
    private object _lock = new object();

    public AsyncResult(AsyncCallback cb, object state)
    {
        _cb = cb;
        _state = state;
    }

    public Object AsyncState
    {
        get { return _state; }
    }

    public bool CompletedSynchronously
    {
        get { return false; }
    }

    public bool IsCompleted
    {
        get { return _completed; }
    }

    public WaitHandle AsyncWaitHandle
    {
        get
        {
            lock (_lock)
            {
                if (_event == null)
                    _event = new ManualResetEvent(IsCompleted);
                return _event;
            }
        }
    }

    public void CompleteCall()
    {
        lock (_lock)
        {
            _completed = true;
            if (_event != null)
                _event.Set();
        }

        if (_cb != null)
            _cb(this);
    }
}

1 个答案:

答案 0 :(得分:1)

迟到,从来没有;我认为以下文章准确解释了您尝试实现的目标:http://blogs.msdn.com/b/jeffva/archive/2010/09/15/rx-on-the-server-part-5-of-n-observable-asp-net.aspx