【发布时间】:2016-08-19 15:07:25
【问题描述】:
我们正在使用 xamarin 表单。在 Android 或 IOS 设备从后台恢复后,我们正在 .net 中进行由计时器触发的 REST 调用。 IOS 上的第一次尝试返回“描述符不是套接字”错误,Android 返回“连接被拒绝”错误。相同的代码在 Windows 中运行良好。所有 3 个平台的未来尝试(每隔几秒钟)都可以正常工作。有没有人看到这个并有解决办法?
代码
//app on resume event
protected async override void OnResume()
{
// Handle when your app resumes
if (MainPage is RootPage)
{
RootPage mainPage = MainPage as RootPage;
if (mainPage.Detail is NavigationPage)
{
NavigationPage nvPage = mainPage.Detail as NavigationPage;
if(nvPage.CurrentPage is ThingsPage)
{
ThingsPage thPage = nvPage.CurrentPage as ThingsPage;
thPage.TurnOnTimer();
}
}
}
}
//code on the page
public void TurnOnTimer()
{
if (viewModel != null)
{
viewModel.ContinueTimer = true;
viewModel.StartAnotherTimer();
}
}
//code in view model
public async void StartAnotherTimer()
{
while (ContinueTimer)
{
try
{
DevicesUpdate devicesUpdate = await DataSource.GetDevices(LocationID, ControllerID, lastDevicesUpdateReceivedAt);
}
catch (Exception ex)
{
}
// Update the UI (because of async/await magic, this is still in the UI thread!)
if (ContinueTimer)
{
await Task.Delay(TimeSpan.FromSeconds(3));
}
}
}
public static async Task<DevicesUpdate> GetDevices(Guid locationID, Guid controllerID, DateTime lastUpdateReceivedAt)
{
DevicesUpdate devicesUpdate = await GetLastUpdatedDevices(controllerID, lastUpdateReceivedAt);
}
//code in view model
public static async Task<DevicesUpdate> GetLastUpdatedDevices(Guid controllerID,
DateTime lastUpdate)
{
System.Net.Http.HttpClient client = new System.Net.Http.HttpClient();
string url = string.Format("http://appname.azurewebsites.net/api/devices?controllerid={1}&lastUpdate={2}"
, Constants.WebServerURL, controllerID, lastUpdate);
System.Net.Http.HttpResponseMessage response = await client.GetAsync(new Uri(url));
string result = await response.Content.ReadAsStringAsync();
if (response.IsSuccessStatusCode)
{
DevicesUpdate devices = JSONHelper.Deserialize<DevicesUpdate>(result);
return devices;
}
else
{
if (response.ReasonPhrase == "UserException")
{
throw new UserException(result);
}
else
{
//throw error because the response from rest api is not a success
throw new System.Net.Http.HttpRequestException(result);
}
}
}
【问题讨论】:
-
您在 App.Resume 事件中执行此操作?你能添加一个小代码 sn-p 来解释你的问题吗?
-
是的..它在 app.resume 事件中。我们正在使用 .net HttpClient 来调用 REST 服务。这是对 HTTP url 的标准 Client.GetAsync() 调用。代码在 PCL 中。
-
您能否更新问题并发布您的
App.OnResume方法和底层服务调用的代码 sn-p(如果不是全部直接在该方法中)。 -
该服务调用不在
App.OnResume中时是否有效? -
我已在问题中添加了代码 sn-p
标签: xamarin xamarin.ios xamarin.android xamarin.forms