如何使用BeginGetRequestStream(C#)中的参数调用AsyncCallback

时间:2017-08-28 14:13:51

标签: c# .net asynccallback get-request

cat

我想用参数调用GetRequestStreamCallback。

有谁知道怎么做?

2 个答案:

答案 0 :(得分:0)

使用lambda而不是方法组。

那是:

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

答案 1 :(得分:0)

使用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版本中都可用。