简体   繁体   English

C#计时器Backgroundworker用户控件

[英]C# timer backgroundworker user controls

I have a C# Windows Form Application that has a menu called Start Download Files and thi menu have then two instantiated user controls(submenu, tab menus). 我有一个C#Windows窗体应用程序,该应用程序具有一个名为“开始下载文件”的菜单,然后该菜单具有两个实例化的用户控件(子菜单,选项卡菜单)。 For each tab (user control) i have a download button and a timer that runs it every 5 minutes. 对于每个选项卡(用户控件),我都有一个下载按钮和一个每5分钟运行一次的计时器。 I am using a private background worker which is created every time the control loads and runs a method to start download the files. 我正在使用一个私有后台工作程序,该工作程序在每次控件加载并运行一种方法开始下载文件时创建。 That gives me a lot of troubles which i still can't find a solution for because: - when i enable the timer for both controls they start the download multiple times for each and i get into concurrency accessing the files or - cross thread exceptions 这给我带来了很多麻烦,我仍然找不到解决方案,因为:-当我为两个控件启用计时器时,它们为每个控件多次启动下载,并且我开始并发访问文件,或者-跨线程异常

Does someone experienced something similar and maybe can give me a hint? 有人经历过类似的事情,也许可以给我提示吗?

My code looks like this: 我的代码如下所示:

 public partial class ucGeneralInfo : UserControl
    {
      private BackgroundWorker backgroundWorker;

      private void TimerDownloadFrequency_Tick(object sender, ElapsedEventArgs e)
        {

            if (backgroundWorker.IsBusy != true)
            {
                backgroundWorker = new BackgroundWorker();
                backgroundWorker.DoWork += new DoWorkEventHandler(backgroundWorker_DoWork);
                backgroundWorker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(backgroundWorker_RunWorkerCompleted);
                backgroundWorker.RunWorkerAsync(Branch);

            }
        }

        private void backgroundWorker_DoWork(object sender, DoWorkEventArgs e)
        {
            Download_Process((string) e.Argument);
        }

        private void Download_Process(string Branch)
        {
         // copying files
         // processing files
        }
     }
}

For concurrent access, use lock . 对于并发访问,请使用lock

 lock(fileLock)
 {
     wc.DownloadFileAsync (/*...*/);
 }


For Cross-thread exception use Invoke . 对于Cross-thread exception使用Invoke

Invoke(new MethodInvoker(delegate
{
      timer.Enable = true;
}));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM