我尝试等待HttpWebRequest完成而无需编写一打AsyncCallbacks。为此,我尝试在Task中处理调用,并在其中使用WaitOne - >以便ui线程不会被阻塞。NotSupportedException当在非UI线程上调用AsyncWaitHandle.WaitOne线程
现在的问题是,每次我打电话时都会出现NotSupportedException,我不明白为什么。有人可以告诉我更多关于这个问题,也许如何解决这个问题?
下面的代码:
Task.Factory.StartNew((x)=>
{
HttpWebRequest request = WebRequest.CreateHttp(baseUri + "/api/" + ControllerName);
request.Method = "POST";
request.ContentType = "application/json";
request.Headers["Session"] = SessionKey;
IAsyncResult GetRequestStreamResult = request.BeginGetRequestStream(null, null);
GetRequestStreamResult.AsyncWaitHandle.WaitOne(); //<-- That causes the exception
using (Stream RequestStream = request.EndGetRequestStream(GetRequestStreamResult))
{
DataContractJsonSerializer serializer = new DataContractJsonSerializer(Parameter.GetType());
serializer.WriteObject(RequestStream, Parameter);
}
问候
克里斯托夫
这相当糟糕。在任务中使用BeginGetRequestStream()没有意义。任务已经是异步的,所以只需使用GetRequestStream()。 –
@HansPassant注意到我在silverlight上下文中。没有像“GetRequestStream”这样的方法。 – christoph