gpt4 book ai didi

C# 异步任务不会继续

转载 作者:行者123 更新时间:2023-12-03 21:58:55 25 4
gpt4 key购买 nike

我有个问题。在我的 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); 之后停止了
现在任务永远不会被执行,所以有些事情出错了!

为什么这不起作用!?

最佳答案

问题:
您的颜色值以“#”开头,即 Convert.ToInt32()无法处理,导致 System.FormatException: Could not find any recognizable digits .该异常“消失”了,因为它发生在异步状态机内部。

修复:
砍掉前导的“#”,例如像这样:

int rgb = Convert.ToInt32(item.Color.Substring(1), 16);

关于C# 异步任务不会继续,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60722649/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com