Click here to Skip to main content
15,886,518 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hello everyone,

I am creating a WPF app where I want to have a global bool im assuming, on the first button click I’ll set this bool to true and I want it to run a task (continuously call an API method) until I click the button again and it stops it. What would be the best way to do this?
C#
private bool running = false;

private async void BtnTrade1_Buy_Click(object sender, RoutedEventArgs e)
{
    if (!running)
    {
        running = true;
    }
    else
        running = false;

    if (running)
    {
        RunningNrunnin(running);
        //tradeClient.GetTradeHistory();
    }
}

public void RunningNrunnin(bool running)
{
    if (running)
    {
        Task task = new Task(() =>
        {
            while (running)
            {
                GetTradeHistory();
                Thread.Sleep(2000);
            }
        });
        task.Start();
    }
}

I agree with using a CancellationToken.
How can I use it with the same button? I been trying a bunch of things but haven't done it yet.
C#
public async Task<int> GetTradeTest(CancellationToken cancelToken)
{
    int i = 0;
    // while(cancelToken == null)
    // {
        await Task.Delay(1000);
        i++;
    // }
    return i;
}

public Task<int> ExecuteOrCancel(CancellationToken token)
{
    Task<int> task = null;

    task = Task.Run(() =>
    {
        int result = 0;
        while (true)
        {
            if (token.IsCancellationRequested)
            {
                // throw new TaskCanceledException(task);
            }

            Thread.Sleep(1000);
            result++;
        }
        return result;
    });
    
    return task;
}

public async Task<int> GetTradeTest(CancellationToken cancelToken)
{
    int i = 0;
    // while(cancelToken == null)
    // {
        await Task.Delay(1000);
        i++;
    // }
    return i;
}

public Task<int> ExecuteOrCancel(CancellationToken token)
{
    Task<int> task = null;

    task = Task.Run(() =>
    {
        int result = 0;
        while (true)
        {
            if (token.IsCancellationRequested)
            {
                // throw new TaskCanceledException(task);
            }

            Thread.Sleep(1000);
            result++;
        }
        return result;
    });
    
    return task;
}

    try
    {
        cancellationToken = new CancellationTokenSource();
        lblTest.Content = "Starting...";
    
        // int counterTest = await tradeClient.GetTradeTest(cancellationToken.Token);
        var counterTest = tradeClient.ExecuteOrCancel(cancellationToken.Token);
        lblTest.Content = "Started: " + counterTest;
                
        // if (running)
        // {
            // tradeClient.RunningHarkins(running);
            // tradeClient.GetTradeHistory();
        // }
    }
    catch (Exception ex)
    {
        // MessageBox.Show(ex.Message);
        lblTest.Content = "Canceled";
    }
    // cancellationToken = null;
}


What I have tried:

Tried coding, threading, tasks, using a global bool I can get that to turn true and false on button click but then i cant get the method to keep checking the bool status while its running. I know i have a good start just need a few finishing touches
Posted
Updated 18-May-20 4:09am
v3

I would probably use a cancellationtoken - have a look at these for ideas

How to: Cancel a Task and Its Children | Microsoft Docs[^]

Cancel asynchronous operations in C# | John Thiriet[^]
 
Share this answer
 

Try doing something like this


C#
private async void BtnTrade1_Buy_Click(object sender, RoutedEventArgs e)
{
    if(isRunning)
    {
        cts.Cancel();
        isRunning = false;
        return;
    }
    isRunning = true;
    cts = new CancellationTokenSource();
    try
    {
        await RunningNrunnin(cts.Token);
    }
    catch (OperationCanceledException ex)
    {
        //Do something here if necessary
    }

}


public async Task RunningNrunnin(CancellationToken token)
{
        while (true)
        {
            await Task.Run(() => GetTradeTest(token));
            await Task.Delay(2000, token);
        }
}
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900