我有问题。在我的Xamarin Forms应用程序中,我具有以下代码来切换网络中的设备:
public ICommand cmdTogglePower
{
get
{
return new Command<int>((x) => TogglePower_Handler(x));
}
}
public Task TogglePower_Handler(int Id)
{
return TogglePower(Id);
}
private async Task TogglePower(int Id)
{
foreach (var item in knownDeviceList)
{
if (item.Id == Id)
{
if (item.State == 1) { item.State = 0; }
else if (item.State == 0) { item.State = 1; }
switch (item.State)
{
case 1:
item.StateShown = "Turned on";
item.PowerStateColor = "#FFFFFF";
item.DeviceImageColor = item.Color;
break;
case 0:
item.StateShown = "Turned off";
item.PowerStateColor = "#707070";
item.DeviceImageColor = "#707070";
break;
}
foreach (var device in App.KnownDeviceList)
{
if (device.Id == Id)
{
device.State = item.State;
int rgb = Convert.ToInt32(item.Color, 16);
int r = (rgb & 0xff0000) >> 16;
int g = (rgb & 0xff00) >> 8;
int b = (rgb & 0xff);
string status = await App.RestService.SendCommand(r, g, b);
break;
}
}
break;
}
}
}
我希望应用程序调用Task SendCommand,该任务通过网络将https命令发送到另一个类中的该设备。这是该任务的代码:
public async Task<string> SendCommand(int Red, int Green, int Blue)
{
var postData = new List<KeyValuePair<string, string>>();
postData.Add(new KeyValuePair<string, string>("red", Red.ToString()));
postData.Add(new KeyValuePair<string, string>("green", Green.ToString()));
postData.Add(new KeyValuePair<string, string>("blue", Blue.ToString()));
var content = new FormUrlEncodedContent(postData);
var weburl = "mysite.org";
string response = await PostResponseSendCommand(weburl, content);
return response;
}
public async Task<string> PostResponseSendCommand(string weburl, FormUrlEncodedContent content)
{
var response = await client.PostAsync(weburl, content);
var responseString = await response.Content.ReadAsStringAsync();
return responseString;
}
但是代码在int rgb = Convert.ToInt32(item.Color, 16);
之后停止
现在任务永远不会执行,所以出问题了!
为什么这不起作用!?
答案 0 :(得分:5)
问题:
您的颜色值以“#”开头,Convert.ToInt32()
无法处理,它会导致System.FormatException: Could not find any recognizable digits
。而且该异常“消失”了,因为它发生在异步状态机内部。
修复程序:
砍掉开头的“#”,例如像这样:
int rgb = Convert.ToInt32(item.Color.Substring(1), 16);