【发布时间】:2021-12-27 18:19:42
【问题描述】:
之前可能有人问过它的要点,但我完全迷路了,所以我正在寻找一些个人指导。一直在尝试使用 WinForms 和 Yahoo API 为有趣的人制作股票跟踪器应用程序。尝试获取它,以便您可以输入跟踪器符号,它将创建一个新的标签,该标签将不时地自我更新。但是,它不断给我有关“跨线程操作无效”的错误消息。我试图做一些谷歌搜索,但是,是的,完全迷路了。大部分代码都写到这里了,希望大家能看懂。
using System;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using YahooFinanceApi;
namespace stockpoging4
{
public partial class Form1 : Form
{
public Form1()
{
System.Globalization.CultureInfo.DefaultThreadCurrentUICulture = System.Globalization.CultureInfo.GetCultureInfo("en-US");
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
using (Prompt prompt = new Prompt("Enter the ticker symbol", "Add ticker"))
{
string result = prompt.Result;
result = result.ToUpper();
if (!string.IsNullOrEmpty(result))
{
do_Things(result);
}
}
}
public async Task<string> getStockPrices(string symbol)
{
try
{
var securities = await Yahoo.Symbols(symbol).Fields(Field.RegularMarketPrice).QueryAsync();
var aapl = securities[symbol];
var price = aapl[Field.RegularMarketPrice];
return symbol + " $" + price;
}
catch
{
return "404";
}
}
public async void do_Things(string result)
{
string price;
Label label = null;
if (label == null)
{
price = await getStockPrices(result);
label = new Label() { Name = result, Text = result + " $" + price };
flowLayoutPanel2.Controls.Add(label);
}
else
{
Thread testThread = new Thread(async delegate ()
{
uiLockingTask();
price = await getStockPrices(result);
label.Text = result + " $" + price;
label.Update();
});
}
System.Timers.Timer timer = new System.Timers.Timer(10000);
timer.Start();
timer.Elapsed += do_Things(results);
}
private void uiLockingTask() {
Thread.Sleep(5000);
}
}
}
【问题讨论】:
-
我在
label == null中看不到任何关系,并且在使用label的线程上执行某些操作... 在 UI 线程上使用 async/await 创建一个简单的“定时器/循环” (没有阻塞)很容易。我试着举个例子。