【问题标题】: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。
有人知道怎么做吗?
【问题讨论】:
标签:
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);
...
}
GetRequestStreamAsync 和 async/await 适用于所有受支持的 .NET 版本。