locked
C# Using a task to call a method continously until cancel token valid. RRS feed

  • Question

  • User-544325736 posted

    Hello every1, I have a C# app where I would like to call a method over and over until the user creates a cancel request on a thread in the background. I currently had it so I can call a action (a counter) and update the GUI each second but when I try to do this same thing with a method call it executes only once.

    // counter task action
    private void StartWork()
            {
                cancellationToken = new CancellationTokenSource();
    
                //task = Task.Factory.StartNew(async () =>
                Task.Run(async () => 
                {
                    while (true)
                    {
                        cancellationToken.Token.ThrowIfCancellationRequested();
    
                        await lblTest.Dispatcher.InvokeAsync(() => lblTest.Content = "Running2: " + counter);
                        counter++;
                        await Task.Delay(1000);
                    }
                }, cancellationToken.Token);
            }
    // Here is the method I want to call continously until canceled
    private async void HistoryTest()
            {
                cancellationToken = new CancellationTokenSource();
    
                task = Task.Factory.StartNew(async () =>
                {
                    while (true)
                    {
                        cancellationToken.Token.ThrowIfCancellationRequested();
    
                        await Client2.GetHistory();
                        await Task.Delay(2000);
                    }
                }, cancellationToken.Token);
               
            }
    public async Task GetHistory()
            {
                try
                {
                    var response = await Client.Service.GetDataAsync
                        (
                            ProductType.BtcUsd,
                            5,
                            1
                        );
                }
                catch(Exception)
                {
                    throw;
                }
            }

    Monday, May 18, 2020 6:42 PM

All replies