C# 如何使web服务后同步
我将首先了解异步性和非UI冻结应用程序的重要性。我非常喜欢的整个async/await世界,甚至APM,或者使用C# 如何使web服务后同步,c#,web-services,windows-phone-8,synchronous,C#,Web Services,Windows Phone 8,Synchronous,我将首先了解异步性和非UI冻结应用程序的重要性。我非常喜欢的整个async/await世界,甚至APM,或者使用任务做繁重的工作 这很好,但我有一个场景,我真的需要等待web服务发布完成,然后继续 public void DoSomeWorkNow() { // Do stuff... // Do more stuff... // Make the web service call.. // The request should finish and I should c
任务做繁重的工作
这很好,但我有一个场景,我真的需要等待web服务发布完成,然后继续
public void DoSomeWorkNow()
{
// Do stuff...
// Do more stuff...
// Make the web service call..
// The request should finish and I should continue doing stuff....
// Do stuff...
}
我不能使用async/await,即使我愿意,它也不能解决问题。
我可以使用Task.fromsync,但您可以参考我遇到的一个问题
我不能使用第三方库,因为这是一个库,不需要第三方依赖项
这确实是一个同步的原因,不会涉及细节,这不是一个设计问题,这是一个设计特性
使用WebRequestBegin/End操作,请求/响应与回调一起发生。
那很好,很好用。现在没有同步调用web服务的API,Windows Phone 8 SDK不支持GetRequest/GetRespone
我尝试使用互斥体并调用Wait
方法,该方法在web服务类中调用Mutex.WaitOne()
假定它将暂停调用方法,直到最后一个完成请求并获得响应的回调发出释放信号
理论上它应该可以工作,但是当调用WaitOne()
时,最后一个回调永远不会返回来执行该任务
然后我想使用IAsyncResult
从BeginXyz/EndXyz方法返回值,在while循环中检查IsComplete
,如果为true,则中断以继续。没有成功
所以,我想知道,有没有一个可行的有效解决方案来同步调用web服务
搜索Google和stackoverflow时,没有返回有效的解决方案
已更新
以下是我尝试过的一些代码:
public void ExecuteRequest(string url, string requestData, string filePath)
{
WebRequest request = WebRequest.Create(new Uri(url));
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
((HttpWebRequest)request).UserAgent = "Tester";
request.Headers["UserName"] = "Tester";
DataWebRequest webRequestState = new DataWebRequest
{
Data = requestData,
FileName = filePath,
Request = request
};
IAsyncResult requestResult = request.BeginGetRequestStream(ar =>
{
DataWebRequest webRequestData = (DataWebRequest )ar.AsyncState;
HttpWebRequest requestStream = (HttpWebRequest)webRequestData.Request;
string data = webRequestData.Data;
// Convert the string into a byte array.
byte[] postBytes = Encoding.UTF8.GetBytes(data);
try
{
// End the operation
// Here the EndGetRequestStream(ar) throws exception System.InvalidOperationException:
// Operation is not valid due to the current state of the object
using (Stream endGetRequestStream = requestStream.EndGetRequestStream(ar))
{
// Write to the request stream.
endGetRequestStream.Write(postBytes, 0, postBytes.Length);
}
requestStream.BeginGetResponse(GetResponseCallback, webRequestData);
}
catch (WebException webEx)
{
WebExceptionStatus status = webEx.Status;
WebResponse responseEx = webEx.Response;
Debug.WriteLine(webEx.ToString());
}
}, webRequestState);
// The below while loop is actually breaking as the IsCompleted is true, but an
// exception System.InvalidOperationException is thrown after a while
while (true)
{
if (requestResult.IsCompleted) break;
}
IAsyncResult responseResult = request.BeginGetResponse(ar =>
{
DataWebRequest webRequestData = (DataWebRequest)ar.AsyncState;
HttpWebRequest httpWebRequest = (HttpWebRequest)webRequestData.Request;
try
{
// End the operation
using (HttpWebResponse response = (HttpWebResponse)httpWebRequest.EndGetResponse(ar))
{
HttpStatusCode rcode = response.StatusCode;
Stream streamResponse = response.GetResponseStream();
StreamReader streamRead = new StreamReader(streamResponse);
// The Response
string responseString = streamRead.ReadToEnd();
if (!string.IsNullOrWhiteSpace(webRequestData.FileName))
{
FileRepository fileRepo = new FileRepository();
fileRepo.Delete(webRequestData.FileName);
}
Debug.WriteLine("Response : {0}", responseString);
// Maybe do some other stuff....
}
}
catch (WebException webEx)
{
WebExceptionStatus status = webEx.Status;
WebResponse responseEx = webEx.Response;
Debug.WriteLine(webEx.ToString());
}
}, webRequestState);
// This while loop never actually ends!!!
while (true)
{
if (responseResult.IsCompleted) break;
}
}
谢谢。向我们展示您不起作用的代码。这是你的问题得到有意义回答的唯一希望。我已经多次操纵代码,现在它只是异步的。但给我几分钟准备一下。我将使用IAsyncResult返回执行最符合逻辑的解决方案,并检查IsCompleted属性。您可以看到我尝试过的一些代码,但不确定它是否正确!您不能只使用同步调用,即GetRequestStream
而不是BeginGetRequestStream
etch您是否曾在Windows Phone 8中使用WebRequest进行web服务调用?没有这样的方法。只有APM方法可用。