【发布时间】:2014-08-29 10:56:50
【问题描述】:
我有一个 C# windows 窗体应用程序。我想通过从网上获取信息来更新一些标签。我想使用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,UI 会挂起。如何使用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。它不会阻塞用户界面。 -
您使用的是什么版本的 .NET?如果您使用的是 .NET 4.5,则可以使用 async/await 和
Task.Delay -
@SriramSakthivel 最好也在这里提供有关 UI 线程问题的建议 msdn.microsoft.com/en-us/magazine/cc164015.aspx
-
除了系统计时器,您可能还需要 ReportProgress 函数来更新 UI 线程中的标签:msdn.microsoft.com/en-us/library/…
-
我不需要,@Steve 做到了。 :)
标签: c# multithreading asynchronous backgroundworker