0

Below is the Service method that i call.... after i have called the service... my net goes off and i cancel the token

Which means after i have hit the service i cancel the token... is there a way to cancel the service i have called...

below is my code

    public async Task<List<MeritData>> GetSyncupData(string Id, string BusinessDate, CancellationToken cancellationToken)
    {
        List<MeritData> PendingData = new List<MeritData>();
        HttpResponseMessage responseMessage = null;
        try
        {
            cancellationToken.ThrowIfCancellationRequested();

            var api = RestService.For<IInventoryMeritStatusApi>(_httpClient);
            responseMessage = await api.GetMeritData(Id, BusinessDate, cancellationToken).ConfigureAwait(false);

            if (cancellationToken.IsCancellationRequested)
                cancellationToken.ThrowIfCancellationRequested();

            if (responseMessage.StatusCode == System.Net.HttpStatusCode.OK)
            {
               
            // my code on success

            }
        }
        catch (SocketException SocketEx)
        {
            ServiceException serviceException = new ServiceException("SocketException", SocketEx);
            throw serviceException;
        }
        catch (HttpRequestException httpReqEx)
        {
            ServiceException serviceException = new ServiceException("NoInternet", httpReqEx);
            throw serviceException;
        }
        catch (ServiceException serviceEx)
        {
            ServiceException serviceException = new ServiceException("NoInternet", serviceEx);
            throw serviceException;
        }
        catch (OperationCanceledException ex)
        {
            Console.WriteLine("TaskCanceledException GetProduct");
            throw ex;
        }
        catch (Exception ex)
        {
            throw ex;
        }
        return PendingData;
    }

after the line

            responseMessage = await api.GetMeritData(Id, BusinessDate, cancellationToken).ConfigureAwait(false);

is executed i switch off the net and call cancellationTokenSource.Cancel();

it takes a long time and finally get a "httprequestexception" not a token cancelled exception

how do i solve this ? i want to cancel the call to the webservice when token.Cancel is called

MainakChoudhury
  • 502
  • 1
  • 7
  • 23
  • Can you please try to pass a `CancellationTokenSource` to `api.GetMeritData` instead of `cancellationToken`? See the code example [here](https://learn.microsoft.com/en-us/dotnet/standard/threading/cancellation-in-managed-threads#code-example). – nevermore Jul 01 '20 at 07:04
  • @JackHua-MSFT In the example they are passing cts.Token...cts is the TokenSource – MainakChoudhury Jul 01 '20 at 09:51
  • Oh, sorry I misread it. Will update you if I find a solution. – nevermore Jul 03 '20 at 01:56

0 Answers0