我正忙于在 Windows Forms 中開發股票跟蹤器應用程式,以獲取樂趣。為了優化我的代碼,我決定重寫 main 函式,使所有內容保持最新。我認為選擇正確的行并從那里開始作業會更容易,而不是為正確的控制元件尋找所有控制元件。問題是:它不斷跳過我要運行的任務,并且不再更新它。我已經嘗試了很多我在互聯網上找到的東西,但我無法讓它作業。所以我恢復到我原始代碼的最簡單形式,看看你們是否有想法。這就是這一切的本質:
public async void KeepUpdatingEverything(List<object> positionInfo, List<string> tickerList)
{
foreach (string ticker in tickerList)
{
//code that gets the right row
List<object> priceInfo = await GetStockPrices(ticker));
//code that updates all the labels
}
}
這個想法是,當呼叫 KeepUpdating 函式時,它會檢查帶有股票的串列,獲取每個股票的價格,然后更新所有相關標簽。但我似乎無法讓它作業,因為它一直跳過異步呼叫。有任何想法嗎?
KeepUpdatingEverything 在輸入第一個股票時被呼叫一次,之后它只是不斷更新股票串列。
private async void button1_Click(object sender, EventArgs e)
{
string ticker;
using (Prompt prompt = new Prompt("Enter the ticker symbol", "Add ticker"))
{
ticker = prompt.Result;
ticker = ticker.ToUpper();
if (!string.IsNullOrEmpty(ticker))
{
using (Prompt prompt2 = new Prompt("Enter your volume", "Add ticker"))
{
if (Int32.TryParse(prompt2.Result, out int volume) == true)
{
using (Prompt prompt3 = new Prompt("Enter your buy price", "Add ticker"))
{
if (Double.TryParse(prompt3.Result, out double buyPrice) == true)
{
try
{
List<object> priceInfo = await GetStockPrices(ticker);
FillTickerLabel(ticker);
List<object> positionInfo = GetPositionVars(ticker, volume, buyPrice, Convert.ToDouble(priceInfo[1]));
FillPositionLabel(ticker, priceInfo[0].ToString(), positionInfo);
List<object> changeInfo = GetChangeVars(ticker, priceInfo);
FillChangeLabels(ticker, priceInfo[0].ToString(), changeInfo);
List<string> tickerList = new List<string>();
tickerList.Add(ticker);
if (tickerList.Count <= 1)
{
_cancellationToken = new CancellationTokenSource();
_runningTask = StartTimer(() => KeepUpdatingEverything(positionInfo, tickerList), _cancellationToken);
}
}
catch
{
MessageBox.Show("Ticker does not exist, or entered incorrect value somewhere else");
}
}
else
{
MessageBox.Show("You did not enter one of the textboxes correctly");
}
}
}
else
{
MessageBox.Show("You did not enter one of the textboxes correctly");
}
}
}
else
{
MessageBox.Show("You did not enter one of the textboxes correctly");
}
}
}
最后,StartTimer 函式:
private async Task StartTimer(Action action, CancellationTokenSource cancellationTokenSource)
{
try
{
while (!cancellationTokenSource.IsCancellationRequested)
{
await Task.Delay(5000, cancellationTokenSource.Token);
action();
}
}
catch (OperationCanceledException) { }
}
uj5u.com熱心網友回復:
async void意味著您不會回傳呼叫者可以執行的任務await。
你應該async Task像這樣使用
public async Task KeepUpdatingEverything(List<object> positionInfo, List<string> tickerList)
uj5u.com熱心網友回復:
更新漢斯的回答。您需要await在父方法中呼叫。
await KeepUpdatingEverything(...)
它會等到完成。
順便說一句,這不是await進入 foreach的最佳方式。將所有任務結果放入串列或陣列中將更容易await。
await Tasks.WhenAll(tasks);
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/377472.html
上一篇:如何在異步中獲取最新資料?
