简体   繁体   中英

Awaiting data from Xamarin/MAUI IOS Healthkit query

I'm not familiar with threads, awaiting and delegates etc. I have the following problem. This method:

public HKSample[] Get(DateTime from, DateTime? to)
    {
        HKSample[] result = null;

        var restingHeartRateType = HKQuantityType.Create(HKQuantityTypeIdentifier.RestingHeartRate);

        var predicate = HKQuery.GetPredicateForSamples(from.ToNSDate(), to.HasValue ? to.Value.ToNSDate() : null, HKQueryOptions.None);

        var q = new HKSampleQuery(
            restingHeartRateType,
            predicate,
            500,
            new NSSortDescriptor[] { },
            new HKSampleQueryResultsHandler(
                (HKSampleQuery query2, HKSample[] results, NSError error2) =>
            {
                result = results;
            }));

        healthKitStore.ExecuteQuery(q);

        return result;
    } 

returns before the resultshandler sets the method return variable. How can I wait for the result variable to be set before finishing the method?

I'm doing a lot of healthkit investigation, I'm shocked at how little is sampled / documented for xamarin/maui c#.

In general, if a task or function takes a long time, we generally recommend executing code asynchronously. Otherwise, the program is prone to crash or blocked.

If you want to wait for a function to finish before performing subsequent operations, you can use Async and await to do so.

Please refer to the following code:

   async void callMethod() { 

        Task<HKSample[]> task = Get(from, to);

        HKSample[] hKs  = await task;

    }

    public async  Task<HKSample[]>  Get(DateTime from, DateTime? to)
    {
        HKSample[] result = null;

        var restingHeartRateType = HKQuantityType.Create(HKQuantityTypeIdentifier.RestingHeartRate);

        var predicate = HKQuery.GetPredicateForSamples(from.ToNSDate(), to.HasValue ? to.Value.ToNSDate() : null, HKQueryOptions.None);

        var q = new HKSampleQuery(
            restingHeartRateType,
            predicate,
            500,
            new NSSortDescriptor[] { },
            new HKSampleQueryResultsHandler(
                (HKSampleQuery query2, HKSample[] results, NSError error2) =>
                {
                    result = results;
                }));

        healthKitStore.ExecuteQuery(q);

        return result;
    }

For more about async and await, you can check: Asynchronous programming with Async and Await (Visual Basic) and Async And Await In C# .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM