【问题标题】:How to call AsyncCallback with a parameter in an BeginGetRequestStream (C#)如何在 BeginGetRequestStream (C#) 中使用参数调用 AsyncCallback
【发布时间】:2018-02-05 20:20:38
【问题描述】:
    public void SendPost(string code)
    {
        // Create the web request object
        HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(Resource.Url);
        webRequest.Method = "POST";
        webRequest.ContentType = "application/x-www-form-urlencoded";

        //Start the request
        webRequest.BeginGetRequestStream(new AsyncCallback(GetRequestStreamCallback), webRequest);
    }

我想用参数调用 GetRequestStreamCallback。

有人知道怎么做吗?

【问题讨论】:

  • 你为什么用BeginGetRequestStream而不是GetRequestStreamAsync?它适用于所有受支持的 .NET 版本

标签: c# .net asynccallback get-request


【解决方案1】:

使用 lambda 而不是方法组。

即:

webRequest.BeginGetRequestStream(new AsyncCallback(result => GetRequestStreamCallback(result, someParameter)), webRequest);

【讨论】:

    【解决方案2】:

    使用 GetRequestStreamAsync 代替 BeginGetRequestStream。有了它,您可以使用async/await 关键字等待操作异步完成并继续执行:

    public async Task SendPost(string code)
    {
        // Create the web request object
        HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(Resource.Url);
        webRequest.Method = "POST";
        webRequest.ContentType = "application/x-www-form-urlencoded";
    
        //Start the request
        var stream=await webRequest.GetRequestStream(webRequest);
        MyStreamProcessingMethod(stream);
        ...
    }
    

    GetRequestStreamAsyncasync/await 适用于所有受支持的 .NET 版本。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-04-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-03-23
      • 1970-01-01
      相关资源
      最近更新 更多