关于 HttpWebRequest 的 EndGetResponse

发布于 2024-12-04 12:01:37 字数 1160 浏览 0 评论 0原文

我正在使用异步调用与我的服务器进行通信。我编写了一些组件来收集所有未经授权的请求,并在用户登录后重新发送它们。我编写了一些测试来生成 10 个线程,这些线程在未经授权的情况下发送一些请求。然后我等待 20 秒并进行授权,然后等待请求成功完成。但是问题出现在我在回调方法中调用的 EndGetResponse 方法。我这样做了:

public void InternalCallback(IAsyncResult result)
{
    try
    {
        RequestState state = (RequestState)result.AsyncState;
        IHttpWebRequest request = state.Request;    

        using (IHttpWebResponse response = responseGetter.GetResponse(request, result))
        {
           // ...
        }
     }
     // ...
}

因此,我创建了一些自定义类 RequestState,它具有我需要的一些更高级别的回调,并且它具有我将用来调用 EndGetResponse 方法的请求。但这样我得到了错误:

IAsyncResult object was not returned from the corresponding asynchronous method.

我改变了这一点,所以现在我的回调类中有 Request 字段,我在调用 BeginGetResponse 之前设置了该字段,并且在回调中调用 EndGetResponse 时使用该 Request 字段。

public void InternalCallback(IAsyncResult result)
{
    try
    {                                   
        using (IHttpWebResponse response = responseGetter.GetResponse(this.Request, result))
        {
           // ...
        }
     }
     // ...
}

这一新解决方案有效吗?你能建议这是一个好方法吗?或者我应该怎么做?

I'm using asynchronous calls for communication to my server. I written some component to collect all unauthorized requests and to resend them after user logs in. I written some test to produce 10 threads that are sending some requests without first being authorized. Than I wait for 20 seconds and do authorization and after that I wait for request to successfully finish. But problem appeared at EndGetResponse method which I call in my callback method. I done that this way:

public void InternalCallback(IAsyncResult result)
{
    try
    {
        RequestState state = (RequestState)result.AsyncState;
        IHttpWebRequest request = state.Request;    

        using (IHttpWebResponse response = responseGetter.GetResponse(request, result))
        {
           // ...
        }
     }
     // ...
}

So, I made some custom class RequestState which has some higher level callbacks I need and it has request which I'll use to call EndGetResponse method. But this way I got error:

IAsyncResult object was not returned from the corresponding asynchronous method.

I changed this so I now have Request field in my callback class which I set before calling BeginGetResponse and I use that Request field when calling EndGetResponse in my callback.

public void InternalCallback(IAsyncResult result)
{
    try
    {                                   
        using (IHttpWebResponse response = responseGetter.GetResponse(this.Request, result))
        {
           // ...
        }
     }
     // ...
}

Is this new solution valid one? Can you suggest is this good way to do this or how should I do this?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文