[英]How to solve targetinvokationexception while consuming wcf webservices in xamarin.forms?
我在xamarin.forms中使用WCF soap Web服務。 我添加了來自Visual Studio的服務參考,該參考生成了異步操作。 我使用以下代碼來使用Web服務
Service1Client dataCommunicator = new Service1Client();
dataCommunicator.GiveFeedbackCompleted += new EventHandler<GiveFeedbackCompletedEventArgs>(GiveFeedbackCallback);
dataCommunicator.GiveFeedbackAsync(editPhoneF.Text, monuments[pickerMonument.SelectedIndex], editRemarks.Text, imei);
}
private async void GiveFeedbackCallback(object sender, GiveFeedbackCompletedEventArgs e)
{
if (e.Result)
{
await DisplayAlert("Success", "Thank you for your valuable comments", "Ok");
}
else
{
await DisplayAlert("Oops!!", "Internal server error, please try again later", "Ok");
}
}
當我在模擬器上對其進行測試時,我只是坐着等待答復,而當我嘗試使用像Android手機這樣的手機時,就會出現錯誤,即targetinvocationexception。 我應該怎么做才能解決這個問題?
由於多種原因,這不是一個好的實現。 首先,您正在使用async void
處理異步完成事件,該事件將靜默忽略引發的任何異常。 其次,異步/完成模式不適用於單次異步調用。 第三,對於大多數情況(包括此情況),由異步/完成模式產生的代碼確實很混亂。
相反,您應該使用Task.Factory.FromAsync<>()
幫助器,它將大大簡化您的代碼並解決這些問題。 對於您來說,它看起來像這樣:
<Button Click="Button_Click" Text="Click Me"/>
...
async void Button_Click(object sender, EventArgs eventArgs) {
Service1Client dataCommunicator = new Service1Client();
try {
bool result =
await Task.Factory.FromAsync<string, Monument, string, IMEI, bool>(
dataCommunicator.BeginGiveFeedback,
dataCommunicator.EndGiveFeedback,
editPhoneF.Text,
monuments[pickerMonument.SelectedIndex],
editRemarks.Text,
imei);
if (e.Result) {
await DisplayAlert("Success", "Thank you for your valuable comments", "Ok");
} else {
await DisplayAlert("Internal server error", "Please try again later.", "Ok");
}
} catch (Exception ex) {
await DisplayAlert("Server communication error", "Please try again later. ERROR: " + ex.GetType().Name, "Ok");
}
}
請注意,我在這里使用async void
,您可能會認為這樣做與我自己矛盾。 當您在該處理程序中手動捕獲異常時,可以將async void
用於控件的事件處理程序(就像我在示例代碼中所做的那樣)。
我認為Xamarin.Forms中存在一個錯誤,這正在引起問題。 我刪除了服務參考,現在手動使用該服務。 我從下面的鏈接中找到了線索,並使用相同的方式來使用Web服務。
https://stackoverflow.com/questions/14336414/httpclient-soap-c/20108971#20108971
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.