我正在为那些对专业人士来说非常基本的事情挣扎。 我试图为httpWebRequest使用扩展包装器。扩展类看起来像这样:
public static class WebRequestExtensions
{
public static Stream GetRequestStreamWithTimeout(
this WebRequest request,
int? millisecondsTimeout = null)
{
return AsyncToSyncWithTimeout(
request.BeginGetRequestStream,
request.EndGetRequestStream,
millisecondsTimeout ?? request.Timeout);
}
public static WebResponse GetResponseWithTimeout(
this HttpWebRequest request,
int? millisecondsTimeout = null)
{
return AsyncToSyncWithTimeout(
request.BeginGetResponse,
request.EndGetResponse,
millisecondsTimeout ?? request.Timeout);
}
private static T AsyncToSyncWithTimeout<T>(
Func<AsyncCallback, object, IAsyncResult> begin,
Func<IAsyncResult, T> end,
int millisecondsTimeout)
{
var iar = begin(null, null);
if (!iar.AsyncWaitHandle.WaitOne(millisecondsTimeout))
{
var ex = new TimeoutException();
throw new WebException(ex.Message, ex, WebExceptionStatus.Timeout, null);
}
return end(iar);
}
}
我尝试使用包装器方法GetResponseWithTimeout
和GetRequestStreamWithTimeout
,但我不知道如何执行此操作。工作代码应如下所示:
var request = (HttpWebRequest)WebRequest.Create(url);
requestStream = request.GetRequestStreamWithTimeout();
我怎样才能做到这一点?
修改
我试图从扩展类派生主类,让我使用包装器方法,但现在我收到此错误消息:
错误3&#39; chunkedUpload.UploadFile&#39;:无法从静态类派生出来&chunkedUpload.WebRequestExtensions&#39;