Best approach for canceling an expected method before navigating?

I'm working in a Xamarin app, but I think my question is more focused on the .NET and C # framework .

For example, I go to PageOne , and in the constructor called the InitializePageOneData () async method ...

public PageOne()
{
    await InitializePageOneData()
}

      

But just at this moment, while it is waiting for the method to execute, I go to the second page ( PageTwo ), which has other asynchronous operations, but I see that the InitializePageOneData () method does not stop its execution.

My goal is to stop this asynchronous operation before navigating to another page. What's your recommendation?

Note: in an asynchronous operation, I use TaskCompletionSource

:

    private Task<Response> ProcessRequest(Request request)
    {
        tsc = new TaskCompletionSource<Response>();

        eventHandler = (s, e) =>
        {
            try
            {
                _client.ProcessRequestsCompleted -= eventHandler;

                tsc.TrySetResult(e.Result);
            }
            catch (Exception ex)
            {
                _client.ProcessRequestsCompleted -= eventHandler;
                tsc.TrySetException(ex);
            }
        };

        _client.ProcessRequestsCompleted += eventHandler;
        _client.ProcessRequestsAsync(request);

        return tsc.Task;
    }

      

+3


source to share


1 answer


My goal is to stop this asynchronous operation before navigating to another page. What's your recommendation?

Pass to CancellationToken

your async method and monitor this token. If the user wants to go to the second page, use CancellationTokenSource

to cancel this operation.

Example:



private CancellationTokenSource cts = new CancellationTokenSource();
public async Task LoadPageOneAsync()
{
    try
    {
        await InitializePageOneDataAsync(cts.Token)
    }
    catch (OperationCanceledException e)
    {
        // Handle if needed.
    }
}

public async Task InitializePageOneDataAsync(CancellationToken cancellationToken)
{
    cancellationToken.ThrowIfCancellationRequested();
    foreach (var something in collection)
    {
        cancellationToken.ThrowIfCancellationRequested();
        // Do other stuff
    }   
}

      

If you want to cancel, call cts.Cancel()

from PageTwo

:

public async Task LoadPageTwoAsync()
{
    cts.Cancel();
    cts = new CancellationTokenSource();

    await LoadSecondPageAsync();
}

      

+3


source







All Articles