我正在创建一个 WPF 应用程序,我想在其中拥有一个全局 bool 假设,在第一个按钮单击时,我将此 bool 设置为 true,并且我希望它运行任务(连续调用 API 方法),直到我单击按钮再次它停止它。最好的方法是什么?
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();
}
}
添加在下面
我想一遍又一遍地调用一个方法,直到用户在后台的线程上创建一个取消请求。我目前拥有它,所以我可以调用一个动作(一个计数器)并每秒更新一次 GUI,但是当我尝试用一个方法调用来做同样的事情时,它只执行一次。
// 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;
}
}