【发布时间】:2011-04-04 03:01:21
【问题描述】:
(只能使用 .NET 3.5 stock,所以没有任务,没有响应式扩展)
我有,我认为这是一个简单的案例,但我对此感到困惑。
简而言之,我正在将 BeginGetRequestStream 的 IAsyncResult 返回给 BeginMyOperation() 的调用者,并且我想真正将 BeginGetResponse 的 IAsyncResult 发回,它是在调用 EndGetRequestStream 时调用的。
所以我想知道,我该怎么做
public IAsyncResult BeginMyOperation(...)
{
HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(requestUri);
webRequest.Method = "POST";
// This is the part, that puzzles me. I don't want to send this IAsyncResult back.
return webRequest.BeginGetRequestStream(this.UploadingStreamCallback, state);
}
// Only want this to be called when the EndGetResponse is ready.
public void EndMyOperation(IAsyncResult ar)
{
}
private IAsyncResult UploadingStreamCallback(IAsyncResult asyncResult)
{
using (var s = state.WebRequest.EndGetRequestStream(asyncResult))
{
using (var r = new BinaryReader(state.Request.RequestData))
{
byte[] uploadBuffer = new byte[UploadBufferSize];
int bytesRead;
do
{
bytesRead = r.Read(uploadBuffer, 0, UploadBufferSize);
if (bytesRead > 0)
{
s.Write(uploadBuffer, 0, bytesRead);
}
}
while (bytesRead > 0);
}
}
// I really want to return this IAsyncResult to the caller of BeginMyOperation
return state.WebRequest.BeginGetResponse(new AsyncCallback(state.Callback), state);
}
【问题讨论】:
-
@JonSkeet 我相信 JonSkeet 可以回答这个问题.. 叹息。
标签: c# .net asynchronous iasyncresult