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;
}
}
Member
30 Points
231 Posts
C# Using a task to call a method continously until cancel token valid.
May 18, 2020 06:42 PM|ExceedingLife|LINK
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.
Participant
1620 Points
927 Posts
Re: C# Using a task to call a method continously until cancel token valid.
May 18, 2020 07:08 PM|PaulTheSmith|LINK
What do you want to call continuously?
a) HistoryTest - Where is the code that you currently have to call it
b) GetHistory - it looks like it is called continuously
You don't explicitly say it but this is an ASP.Net forum. Are you trying to run this as part of a controller action? If so, this is inherently unreliable. Start your reading into the issue at https://haacked.com/archive/2011/10/16/the-dangers-of-implementing-recurring-background-tasks-in-asp-net.aspx/ and then move to a more up-to-date guide on how to achieve this at https://devblogs.microsoft.com/aspnet/queuebackgroundworkitem-to-reliably-schedule-and-run-background-processes-in-asp-net/