-2

The HTTP async method not working and the data never post when I run this in raspberry pi. The distance monitoring method still running but just the data doesn't post 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);

        }
    }
}
Liam
  • 27,717
  • 28
  • 128
  • 190
Fate
  • 37
  • 6
  • 1
    No [images of code](http://idownvotedbecau.se/imageofcode), please. Images are surprisingly hard to compile and run. Please [edit your question](https://stackoverflow.com/posts/54248776/edit). – ProgrammingLlama Jan 18 '19 at 06:33
  • I have tested your code with a [webhook testing service](https://webhook.site/#/7f7d1414-2ce8-47a8-82d1-e5bf31c7bc71/538c930d-da4b-4bb1-859e-68c47f6ba23a/1), and as you can see the post is successful. It may be because you're using `.Wait()` with `Task.Delay`, which could be causing a deadlock? – ProgrammingLlama Jan 18 '19 at 06:39
  • I suspect your question is a duplicate of [this one](https://stackoverflow.com/questions/13140523/await-vs-task-wait-deadlock). The deadlock is basically caused by the caller waiting for the task, and the task waiting for the caller. – ProgrammingLlama Jan 18 '19 at 06:41
  • Do I just remove the private void Sleep(int NoOfMs) method? – Fate Jan 18 '19 at 06:45
  • That would probably be a good idea. I'm not sure what you're waiting 10 seconds for, really. – ProgrammingLlama Jan 18 '19 at 06:47
  • I remove the method and the data still not posting. I'm sending to azure database – Fate Jan 18 '19 at 06:57
  • Please learn about `async` deadlocks. You are calling Sleep in multiple places, and probably not calling the async methods up the chain correctly. Your post method itself does work if called correctly. – ProgrammingLlama Jan 18 '19 at 06:57
  • even though i remove the sleep method, the data still not posting – Fate Jan 18 '19 at 07:08
  • I call the method in startdistanceMonitoring with await sendtoapi(); – Fate Jan 18 '19 at 07:09
  • And you removed all instances of `Sleep`, replacing them with `await Task.Delay(...)`? – ProgrammingLlama Jan 18 '19 at 07:15
  • ya,except in the run method – Fate Jan 18 '19 at 07:18
  • _"except in the run method"_. Remove it there. – ProgrammingLlama Jan 18 '19 at 07:21
  • still not posting – Fate Jan 18 '19 at 07:25
  • and the status of the sensor will be always the same – Fate Jan 18 '19 at 07:27
  • Sorry. I can't help you. I can confirm that your `sendtoapi()` definitely works, provided you remove the `Sleep` code. If you have a deadlock somewhere, that's up to you to fix. – ProgrammingLlama Jan 18 '19 at 07:29
  • Thank you very much for helping, i will figure out the rest myself – Fate Jan 18 '19 at 07:30
  • 1
    There is a **lot** wrong here. You calling async code and not awaiting it, you also have `async void` methods, these should only ever be used for async event handlers. These should be `async Task`. your calling `Task.Delay(NoOfMs).Wait();` which is a blocking call in a non async context. Basically there isn't much of this code that's right – Liam Jan 18 '19 at 09:16

1 Answers1

2

When you do async/await you basically want to make all(most) of your methods work in an async/await manner. At the moment your mixing async and non async method calls. This is called blocking in an async context and it should be avoided, not least of which because it can lead to deadlocks. I'd suggest you have a read though Async/Await - Best Practices in Asynchronous Programming

In general (and to simplify the problem somewhat) all your methods should have the signature

public async Task method()
{

}

and all your methods should be called:

await method();

Here are a couple of things your doing wrong

private async void startDistanceMonitoring()

Never use async void (these are for async event handlers only)

private void Sleep(int NoOfMs)
{
    Task.Delay(NoOfMs).Wait();
}

this is blocking, this should be

private async Task Sleep(int NoOfMs)
{
    await Task.Delay(NoOfMs);
}

When you call:

startDistanceMonitoring();

startDistanceMonitoring is an async method, yet your not awaiting it. So your program may very well terminate before it's completed. This should be:

await startDistanceMonitoring();

You do this incorrectly all over this block of code. Always call async methods with an await.

Your entry method isn't async, public void Run(IBackgroundTaskInstance taskInstance) should be public async Task Run(IBackgroundTaskInstance taskInstance)

Liam
  • 27,717
  • 28
  • 128
  • 190
  • i cant call the await startdistanceMonitoring() in public void run as it is a public void not a async method,do i need to change it to async also? – Fate Jan 18 '19 at 11:10
  • Yes you do. That's what I'm saying – Liam Jan 18 '19 at 11:21