2
Answers

Can backgroundworker create another upon request?

Ask a question
I keep getting errors when running my app. It keep telling me Im trying to run mutli backgroundworkers at the same time. It seems like the IsBusy is not working. Im basically using the backgroundworker to copy files from A to B over a network. Im using FileSystemWatcher to trigger the function of the start of  the backgroundworker.


  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.ComponentModel;  
  4. using System.Data;  
  5. using System.Diagnostics;  
  6. using System.Drawing;  
  7. using System.Linq;  
  8. using System.Text;  
  9. using System.Threading.Tasks;  
  10. using System.Windows.Forms;  
  11. using System.Threading;  
  12. using System.IO;  
  13.   
  14. namespace WindowsFormsApplication9  
  15. {  
  16.     public partial class Form1 : Form  
  17.     {  
  18.         public static string port;  
  19.         public static string AE;  
  20.         public static string dicompath;  
  21.         public static string finalpath;  
  22.         public static string IPbox;  
  23.         BackgroundWorker m_oWorker;  
  24.         public Form1()  
  25.         {  
  26.             InitializeComponent();  
  27.             m_oWorker = new BackgroundWorker();  
  28.             m_oWorker.DoWork += new DoWorkEventHandler(m_oWorker_DoWork);  
  29.             m_oWorker.ProgressChanged += new ProgressChangedEventHandler(m_oWorker_ProgressChanged);  
  30.             m_oWorker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(m_oWorker_RunWorkerCompleted);  
  31.             m_oWorker.WorkerReportsProgress = true;  
  32.             m_oWorker.WorkerSupportsCancellation = true;  
  33.         }  
  34.         struct DataParameter  
  35.         {  
  36.             public int Process;  
  37.             public int Delay;  
  38.         }  
  39.         private DataParameter _inputparameter;  
  40.   
  41.         private void Form1_Load(object sender, EventArgs e)  
  42.         {  
  43.             AEtitlescp.Text = Properties.Settings.Default.AEtitleSCP;  
  44.             Port1.Text = Properties.Settings.Default.Port1;  
  45.             Ports2.Text = Properties.Settings.Default.Port2;  
  46.             IPBox.Text = Properties.Settings.Default.IPBox;  
  47.             CalledAE.Text = Properties.Settings.Default.CalledAE;  
  48.             CallingAE.Text = Properties.Settings.Default.CallingAE;  
  49.             FileLocation.Text = Properties.Settings.Default.FileLocation;  
  50.             this.Location = new Point(Properties.Settings.Default.PX, Properties.Settings.Default.PY);  
  51.   
  52.           
  53.           
  54.           
  55.           
  56.             this.WindowState = FormWindowState.Minimized;  
  57.             this.Visible = false;  
  58.             Use_Notify(); // Setting up all Property of Notifyicon  
  59.   
  60.               
  61.         }  
  62.         void m_oWorker_ProgressChanged(object sender, ProgressChangedEventArgs e)  
  63.         {  
  64.             //Here you play with the main UI thread  
  65.             //progressBar1.Value = e.ProgressPercentage;  
  66.             //lblStatus.Text = "Processing......" + progressBar1.Value.ToString() + "%";  
  67.         }  
  68.           
  69.   
  70.         private void Use_Notify()  
  71.         {  
  72.             MyNotify.ContextMenuStrip = contextMenuStrip1;  
  73.             MyNotify.BalloonTipText = "Pacs Care Dicom Agent";  
  74.             MyNotify.BalloonTipTitle = "Please check Configuration and start agent...";  
  75.             MyNotify.ShowBalloonTip(1);  
  76.         }  
  77.   
  78.         private void Form1_Resize(object sender, System.EventArgs e)  
  79.         {  
  80.             // Hide The Form when it's minimized  
  81.             if (FormWindowState.Minimized == WindowState)  
  82.                 Hide();  
  83.         }  
  84.         private void MyNotify_DoubleClick(object sender, System.EventArgs e)  
  85.         {  
  86.             // Show the form when Dblclicked on Notifyicon  
  87.             Show();  
  88.             WindowState = FormWindowState.Normal;  
  89.         }  
  90.         private void closeToolStripMenuItem_Click(object sender, EventArgs e)  
  91.         {  
  92.             // Will Close Your Application   
  93.             MyNotify.Dispose();  
  94.             Application.Exit();  
  95.         }  
  96.   
  97.         private void restoreToolStripMenuItem_Click(object sender, EventArgs e)  
  98.         {  
  99.             //Will Restore Your Application   
  100.             Show();  
  101.             WindowState = FormWindowState.Normal;  
  102.         }  
  103.   
  104.         private void settingsToolStripMenuItem_Click(object sender, EventArgs e)  
  105.         {  
  106.             //Settings 1  
  107.             MessageBox.Show("Your Application Settings 1");  
  108.         }  
  109.   
  110.         private void settings2ToolStripMenuItem_Click(object sender, EventArgs e)  
  111.         {  
  112.             //Settings 2  
  113.             MessageBox.Show("Your Application Settings 2");  
  114.         }  
  115.   
  116.         private void MyNotify_MouseDoubleClick(object sender, MouseEventArgs e)  
  117.         {  
  118.   
  119.         }  
  120.   
  121.         private void settingsToolStripMenuItem_Click_1(object sender, EventArgs e)  
  122.         {  
  123.   
  124.         }  
  125.   
  126.         private void fileLocationToolStripMenuItem_Click(object sender, EventArgs e)  
  127.         {  
  128.   
  129.         }  
  130.   
  131.         private void FileLocation_TextChanged(object sender, EventArgs e)  
  132.         {  
  133.   
  134.         }  
  135.   
  136.         private void exitToolStripMenuItem_Click(object sender, EventArgs e)  
  137.         {  
  138.   
  139.   
  140.   
  141.         }  
  142.   
  143.         private void fileLocationToolStripMenuItem_Click_1(object sender, EventArgs e)  
  144.         {  
  145.   
  146.         }  
  147.   
  148.         private void configurationToolStripMenuItem_Click(object sender, EventArgs e)  
  149.         {  
  150.             //var Myform = new Settings();  
  151.             //Myform.Show();  
  152.             WindowState = FormWindowState.Normal;  
  153.             Visible = true;  
  154.   
  155.         }  
  156.   
  157.         private void exitToolStripMenuItem1_Click(object sender, EventArgs e)  
  158.         {  
  159.             Application.ExitThread();  
  160.             Application.Exit();  
  161.              
  162.   
  163.         }  
  164.   
  165.         private void Form1_FormClosing(object sender, FormClosingEventArgs e)  
  166.         {  
  167.             Properties.Settings.Default.Port1 = Port1.Text;  
  168.             Properties.Settings.Default.Port2 = Ports2.Text;  
  169.             Properties.Settings.Default.AEtitleSCP = AEtitlescp.Text;  
  170.             Properties.Settings.Default.IPBox = IPBox.Text;  
  171.             Properties.Settings.Default.CalledAE = CalledAE.Text;  
  172.             Properties.Settings.Default.CallingAE = CallingAE.Text;  
  173.             Properties.Settings.Default.FileLocation = FileLocation.Text;  
  174.             Properties.Settings.Default.PX = this.Location.X;  
  175.             Properties.Settings.Default.PY = this.Location.Y;  
  176.             Properties.Settings.Default.Save();  
  177.   
  178.   
  179.   
  180.   
  181.   
  182.             if (e.CloseReason == CloseReason.UserClosing)  
  183.             {  
  184.                 DialogResult result = MessageBox.Show("Do you really want to exit?""Dialog Title", MessageBoxButtons.YesNo);  
  185.                 if (result == DialogResult.Yes)  
  186.                 {  
  187.                     Environment.Exit(0);  
  188.                 }  
  189.                 else  
  190.                 {  
  191.                     e.Cancel = true;  
  192.                 }  
  193.             }  
  194.             else  
  195.             {  
  196.                 e.Cancel = true;  
  197.             }  
  198.         }  
  199.   
  200.         private void startToolStripMenuItem_Click(object sender, EventArgs e)  
  201.         {  
  202.             ///////////Passing values to another form//////////  
  203.             //DicomMonitor DM = new DicomMonitor();  
  204.             //DM.ShowDialog();  
  205.             //////////SETUP VALUES//////////////////////////////  
  206.             port = Port1.Text;  
  207.             AE = AEtitlescp.Text;  
  208.             dicompath = FileLocation.Text;  
  209.             finalpath = port + " -pm" + " --fork " + " -aet " + AE + " -od " + ((char)34) + dicompath + ((char)34);  
  210.             /////////////////////////////////////////////////////  
  211.             var WatchFolder = dicompath;  
  212.             FileSystemWatcher fsw = new FileSystemWatcher(WatchFolder);  
  213.             fsw.EnableRaisingEvents = true;  
  214.             fsw.IncludeSubdirectories = true;  
  215.             fsw.NotifyFilter = NotifyFilters.FileName | NotifyFilters.LastWrite;  
  216.             fsw.Changed += new FileSystemEventHandler(fsw_Changed);  
  217.             fsw.Created += new FileSystemEventHandler(fsw_Created);  
  218.             //fsw.Renamed += new FileSystemEventHandler(fsw_Renamed);  
  219.             /////////////////////////////////////////////////////  
  220.   
  221.   
  222.             //System.Windows.Forms.MessageBox.Show("Server is running...");  
  223.             //textBox1.Text = otherForm.TextBox1.Text;  
  224.             //string port;  
  225.             //Settings Settings = new Settings(Port1.Text);  
  226.               
  227.   
  228.             ////  
  229.             Process startInfo2 = new Process();  
  230.             startInfo2.StartInfo.CreateNoWindow = true;  
  231.             startInfo2.StartInfo.UseShellExecute = false;  
  232.             startInfo2.StartInfo.RedirectStandardOutput = true;  
  233.             startInfo2.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;  
  234.             startInfo2.StartInfo.FileName = @"C:\dcmtk\bin\storescp-tls.exe";  
  235.             startInfo2.StartInfo.Arguments = finalpath;  
  236.             startInfo2.StartInfo.RedirectStandardOutput = true;  
  237.             //int seconds = await SleepAsync(2000);  
  238.             startInfo2.Start();  
  239.         }  
  240.   
  241.         private void stopToolStripMenuItem_Click(object sender, EventArgs e)  
  242.         {  
  243.             Process startInfo2 = new Process();  
  244.             startInfo2.StartInfo.CreateNoWindow = true;  
  245.             startInfo2.StartInfo.UseShellExecute = false;  
  246.             startInfo2.StartInfo.RedirectStandardOutput = true;  
  247.             startInfo2.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;  
  248.             startInfo2.StartInfo.FileName = @"taskkill";  
  249.             startInfo2.StartInfo.Arguments = @"/f /im storescp-tls.exe";  
  250.             startInfo2.StartInfo.RedirectStandardOutput = true;  
  251.             //int seconds = await SleepAsync(2000);  
  252.             startInfo2.Start();  
  253.             System.Windows.Forms.MessageBox.Show("Server is dead Jim...");  
  254.   
  255.             DicomMonitor DM = new DicomMonitor();  
  256.             DM.Close();  
  257.   
  258.   
  259.   
  260.         }  
  261.           
  262.         private void OKbtn_Click(object sender, EventArgs e)  
  263.         {  
  264.             this.Text = Port1.Text;  
  265.             this.Text = Ports2.Text;  
  266.             this.Text = AEtitlescp.Text;  
  267.             this.Text = IPBox.Text;  
  268.             this.Text = CalledAE.Text;  
  269.             this.Text = CallingAE.Text;  
  270.             this.Text = FileLocation.Text;  
  271.   
  272.   
  273.   
  274.             this.WindowState = FormWindowState.Minimized;  
  275.             this.Visible = false;  
  276.         }  
  277.   
  278.         private void CancelBtn_Click(object sender, EventArgs e)  
  279.         {  
  280.             this.Close();  
  281.         }  
  282.   
  283.         private void button3_Click(object sender, EventArgs e)  
  284.         {  
  285.   
  286.         }  
  287.   
  288.         private void button6_Click(object sender, EventArgs e)  
  289.         {  
  290.               
  291.         }  
  292.   
  293.         private void AEtitlescp_TextChanged(object sender, EventArgs e)  
  294.         {  
  295.   
  296.         }  
  297.   
  298.         private void button1_Click(object sender, EventArgs e)  
  299.         {  
  300.             FolderBrowserDialog fbd = new FolderBrowserDialog();  
  301.             fbd.Description = "Enter Path for images...";  
  302.             if (fbd.ShowDialog() == DialogResult.OK)  
  303.                 MessageBox.Show(fbd.SelectedPath);  
  304.             FileLocation.Text = fbd.SelectedPath;  
  305.         }  
  306.   
  307.         private void textBox2_TextChanged(object sender, EventArgs e)  
  308.         {  
  309.   
  310.         }  
  311.   
  312.         private void groupBox1_Enter(object sender, EventArgs e)  
  313.         {  
  314.   
  315.         }  
  316.   
  317.         private void label3_Click(object sender, EventArgs e)  
  318.         {  
  319.   
  320.         }  
  321.         void m_oWorker_DoWork(object sender, DoWorkEventArgs e)  
  322.         {  
  323.             //NOTE : Never play with the UI thread here...  
  324.   
  325.   
  326.             //time consuming operation  
  327.             //  
  328.             // for (int i = 0; i < 100; i++)  
  329.             for (int i=0; i < 100; i++)  
  330.             {  
  331.                                 ///  
  332.                 {  
  333.                     string filepath = Form1.dicompath;  
  334.                     string[] files = Directory.GetFiles(filepath, "*.*", SearchOption.AllDirectories);  
  335.                     for (int index = 0; index < files.Length; index++)  
  336.                         foreach (string s in files)  
  337.                         {  
  338.                             string fileToProcess = filepath;  
  339.                             m_oWorker.ReportProgress(100 * index / files.Length, fileToProcess);  
  340.   
  341.                             string port;  
  342.                             port = Ports2.Text;  
  343.                             string Host;  
  344.                             Host = IPBox.Text;  
  345.                             //string dicompath = @"C:\MyDir";  
  346.                             string finalpath = Host + " " + port + " " + s;  
  347.                             //textBox1.Text = finalpath;  
  348.                             System.Diagnostics.Process pr = System.Diagnostics.Process.Start(new System.Diagnostics.ProcessStartInfo  
  349.                             {  
  350.                                 CreateNoWindow = true,  
  351.                                 UseShellExecute = false,  
  352.                                 RedirectStandardOutput = true,  
  353.                                 WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden,  
  354.                                 FileName = @"C:\dcmtk\bin\storescu-tls.exe",  
  355.                                 Arguments = finalpath  
  356.   
  357.                             });  
  358.   
  359.                             pr.Start();  
  360.                             pr.WaitForExit();  
  361.                             Thread.Sleep(500);  
  362.                             //File.Move(s, @"C:\MyDels");  
  363.                             //Provider Source Folder Path  
  364.                             string SourceFolder = Form1.dicompath;  
  365.                             //Provide Destination Folder path  
  366.                             //string DestinationFolder = @"C:\MyDels\";  
  367.   
  368.                             var filess = new DirectoryInfo(SourceFolder).GetFiles("*.*");  
  369.   
  370.                             //Loop throught files and Move to destination folder  
  371.                             foreach (FileInfo file in filess)  
  372.                             {  
  373.                                 //delete file if already exists  
  374.                                 //Process.Start("cmd.exe", string.Format("/c del \"{0}", SourceFolder + file.Name));  
  375.   
  376.                                 //Move the file to destination folder  
  377.                                 //file.MoveTo(DestinationFolder + file.Name);  
  378.   
  379.                                 System.IO.File.Delete(s);  
  380.                                 //File.Delete(s);  
  381.   
  382.                             }  
  383.   
  384.                             //pr.WaitForExit();  
  385.                             //Thread.Sleep(50);  
  386.                             m_oWorker.ReportProgress(i);  
  387.   
  388.                             //If cancel button was pressed while the execution is in progress  
  389.                             //Change the state from cancellation ---> cancel'ed  
  390.                             if (m_oWorker.CancellationPending)  
  391.                             {  
  392.                                 e.Cancel = true;  
  393.                                 m_oWorker.ReportProgress(0);  
  394.                                 return;  
  395.                             }  
  396.   
  397.                         }  
  398.   
  399.                     //Report 100% completion on operation completed  
  400.                     if (!m_oWorker.IsBusy)  
  401.                           
  402.                         m_oWorker.ReportProgress(100);  
  403.   
  404.                     else  
  405.                         MessageBox.Show("Can't run the worker twice!");  
  406.                       
  407.                 }  
  408.             }  
  409.         }  
  410.        void fsw_Changed(object sender, FileSystemEventArgs e)  
  411.       
  412.             {  
  413.                 try  
  414.                 {  
  415.                     while (!m_oWorker.IsBusy)  
  416.                         m_oWorker.RunWorkerAsync();  
  417.                 }  
  418.                 catch (Exception ex)  
  419.                 {  
  420.                     MessageBox.Show(ex.Message);  
  421.                 }  
  422.                   
  423.   
  424.   
  425.             //listBox1.Text = (e.FullPath + "Has been added. Sending file now....");  
  426.   
  427.         }  
  428.         void fsw_Created(object sender, FileSystemEventArgs e)  
  429.         {  
  430.             try  
  431.             {  
  432.                 //if (!m_oWorker.IsBusy)  
  433.                 m_oWorker.CancelAsync();  
  434.                 m_oWorker.RunWorkerAsync();  
  435.                   
  436.             }  
  437.             catch (Exception ex)  
  438.             {  
  439.                 //Errors.Text = (ex.Source + "Has been added. Sending file now....");  
  440.             }  
  441.   
  442.             m_oWorker.CancelAsync();  
  443.             m_oWorker.RunWorkerAsync();  
  444.   
  445.             //listBox1.Text = (e.FullPath + "Has been added. Sending file now....");  
  446.   
  447.         }  
  448.         void fsw_Renamed(object sender, FileSystemEventArgs e)  
  449.         {  
  450.             try  
  451.             {  
  452.                 //if (!m_oWorker.IsBusy)  
  453.                 m_oWorker.RunWorkerAsync();  
  454.                 m_oWorker.CancelAsync();  
  455.             }  
  456.             catch (Exception ex)  
  457.             {  
  458.                 Errors.Text = (ex.Source + "Has been added. Sending file now....");  
  459.             }  
  460.   
  461.             m_oWorker.CancelAsync();  
  462.             m_oWorker.RunWorkerAsync();  
  463.   
  464.         }  
  465.         void m_oWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)  
  466.         {  
  467.             //If it was cancelled midway  
  468.             if (e.Cancelled)  
  469.             {  
  470.                 //lblStatus.Text = "Task Cancelled.";  
  471.             }  
  472.             else if (e.Error != null)  
  473.             {  
  474.                 // lblStatus.Text = "Error while performing background operation.";  
  475.             }  
  476.             else  
  477.             {  
  478.                 Errors.Text = "Task Completed...";  
  479.   
  480.             }  
  481.             //btnStartAsyncOperation.Enabled = true;  
  482.             //btnCancel.Enabled = false;  
  483.         }  
  484.           
  485.   
  486.         private void Errors_Click(object sender, EventArgs e)  
  487.         {  
  488.   
  489.         }  
  490.   
  491.         private void tESTMEOUTToolStripMenuItem_Click(object sender, EventArgs e)  
  492.         {  
  493.             DicomMonitor F3 = new DicomMonitor();  
  494.             F3.Show();  
  495.   
  496.   
  497.         }  
  498.     }  
  499. }  

Answers (2)