我有一系列需要以特定順序調用的asyc方法。問題是,所有方法都向WCF服務發出請求。使整個項目通用的WCF調用方法。在WCF調用的回調函數中,我確定WCF調用是否成功。如果WCF調用成功,我需要調用另一種方法。有很多方法要依次調用,一個接一個地調用。異步方法調用 - 維護序列
private Action<string> action;
public void MakeHttpPostRequest(string webserviceURL, string json, Action<string> response)
{
try
{
this.action = response;
if (Microsoft.Phone.Net.NetworkInformation.NetworkInterface.GetIsNetworkAvailable())
{
Uri uri = new Uri(webserviceURL);
byte[] byteArray = System.Text.Encoding.UTF8.GetBytes(json);
string data = Encoding.UTF8.GetString(byteArray.ToArray(), 0, (int)byteArray.Length);
WebClient webClient = new WebClient();
webClient.UploadStringCompleted += new UploadStringCompletedEventHandler(this.WebClient_UploadStringCompleted);
webClient.Headers["Content-type"] = "application/json";
webClient.Encoding = Encoding.UTF8;
webClient.UploadStringAsync(uri, "POST", data);
}
else
{
this.action(string.Empty);
}
}
catch (Exception ex)
{
new ErrorException.ErrorException().HandleError(ex, string.Empty, Global.Modules.General);
}
}
private void WebClient_UploadStringCompleted(object sender, UploadStringCompletedEventArgs e)
{
try
{
// Check whether to invoke any method
if (this.action != null)
{
// Invoke the method passed to MakeHttpPostRequest by it's calling method
this.action(e.Result);
}
}
catch (Exception ex)
{
new ErrorException.ErrorException().HandleError(ex, string.Empty, Global.Modules.General);
}
}
我不認爲寫每個方法不同的回調事件,並調用下一個方法是不錯的主意。
這看起來不像WCF對我?直截了當的webclient。你能澄清一下它是什麼嗎? – AnthonyWJones