2

在异步处理程序中,我从 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);
    }
}
4

1 回答 1

1

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

于 2010-09-23T07:58:29.577 回答