我有一个C#的Windows窗体应用程序。我想根据从web获取的信息更新一些标签。我想使用BackgroundWorker
定期调用一个函数。
public partial class OptionDetails : Form
{
static System.ComponentModel.BackgroundWorker worker = new System.ComponentModel.BackgroundWorker();
static void fun()
{
worker.DoWork += new DoWorkEventHandler(worker_DoWork);
worker.RunWorkerCompleted += worker_RunWorkerCompleted;
worker.WorkerSupportsCancellation = true;
worker.RunWorkerAsync();
}
static void worker_DoWork(object sender, DoWorkEventArgs e)
{ // some work }
static void worker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{ // on completion }
}
如果我使用
Timer
,界面会卡住。如何使用BackgroundWorker
定期调用worker_DoWork
?我的实际代码:
public partial class myform: Form
{
public myform()
{
InitializeComponent();
}
public async Task Periodic(Action func, TimeSpan period, CancellationToken token)
{
while (true)
{
// throws an exception if someone has requested cancellation via the token.
token.ThrowIfCancellationRequested();
func();
// asynchronously wait
await Task.Delay(period);
}
}
public async void hello()
{
await Periodic(getCurrentInfo, TimeSpan.FromSeconds(2), CancellationToken.None);
}
private void myform_Load(object sender, EventArgs e)
{
hello();
}
private void getCurrentInfo()
{
WebDataRetriever wdr = new WebDataRetriever();
string name = "name";
string url = String.Empty;
string[] prices = new string[2];
bool urlExists = url.TryGetValue(name, out url);
if (urlExists)
{
wdr.processurl(); // time consuming function
prices[0] = wdr.price1;
prices[1] = wdr.price2;
System.Globalization.NumberFormatInfo nfo = new System.Globalization.CultureInfo("en-US", false).NumberFormat;
if (prices != null)
{
// change labels
}
}
}
}
System.Windows.Forms.timer
。请使用System.Threading.Timer
或System.Timers.Timer
。这样不会阻塞用户界面。 - Sriram SakthivelTask.Delay
。 - NeddySpaghetti