当我在raspberry pi中运行此HTTP异步方法时,该方法无效,并且数据永不发布。距离监控方法仍在运行,但仅数据未发布Codes
IUltrasonicRangerSensor sensor = DeviceFactory.Build.UltraSonicSensor(Pin.DigitalPin8);
private int distance = 200;
int count = 0;
ILed ledRed = DeviceFactory.Build.Led(Pin.DigitalPin5);
ILed ledGreen = DeviceFactory.Build.Led(Pin.DigitalPin6);
private void Sleep(int NoOfMs)
{
Task.Delay(NoOfMs).Wait();
}
private async void startDistanceMonitoring()
{
await Task.Delay(100);
int distanceRead = 200;
while (true)
{
Sleep(1000);
count++;
distanceRead = sensor.MeasureInCentimeters();
if (distanceRead < 200 && distanceRead > 0)
distance = distanceRead;
await sendtoapi();
}
}
private async Task sendtoapi()
{
using (var client = new HttpClient())
{
var values = new Dictionary<string, string>
{
{ "userName", "qwee" }
};
var content = new FormUrlEncodedContent(values);
var response = await client.PostAsync("https://google.com", content);
Sleep(10000);
var responseString = await response.Content.ReadAsStringAsync();
}
}
public void Run(IBackgroundTaskInstance taskInstance)
{
startDistanceMonitoring();
Sleep(300);
Debug.WriteLine("count = " + count + " ,distance=" + distance);
while (true)
{
if (distance >= 150)
{
Debug.WriteLine("EMPTY LOT");
Sleep(1000);
ledGreen.ChangeState(SensorStatus.On);
ledRed.ChangeState(SensorStatus.Off);
}
}
}
答案 0 :(得分:1)
当您执行async
/ await
时,您基本上希望使所有(大多数)方法都以async
/ await
的方式工作。目前,您的混合异步和非异步方法调用。 This is called blocking in an async
context and it should be avoided,这尤其重要,因为它可能导致死锁。我建议您尽管阅读Async/Await - Best Practices in Asynchronous Programming
通常(为了简化问题)所有,您的方法应具有签名
public async Task method()
{
}
和所有您的方法应称为:
await method();
private async void startDistanceMonitoring()
请勿使用async void
(这些仅用于异步事件处理程序)
private void Sleep(int NoOfMs)
{
Task.Delay(NoOfMs).Wait();
}
这正在阻止,应该是
private async Task Sleep(int NoOfMs)
{
await Task.Delay(NoOfMs);
}
致电时:
startDistanceMonitoring();
startDistanceMonitoring
是一种async
方法,但您尚未等待。因此,您的程序很可能在完成之前终止。应该是:
await startDistanceMonitoring();
您在整个代码块中都这样做不正确。 始终使用async
调用await
方法。
您的输入方法不是async
,public void Run(IBackgroundTaskInstance taskInstance)
应该是public async Task Run(IBackgroundTaskInstance taskInstance)