Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • World
  • Users
  • Groups
Skins
  • Light
  • Cerulean
  • Cosmo
  • Flatly
  • Journal
  • Litera
  • Lumen
  • Lux
  • Materia
  • Minty
  • Morph
  • Pulse
  • Sandstone
  • Simplex
  • Sketchy
  • Spacelab
  • United
  • Yeti
  • Zephyr
  • Dark
  • Cyborg
  • Darkly
  • Quartz
  • Slate
  • Solar
  • Superhero
  • Vapor

  • Default (No Skin)
  • No Skin
Collapse
Code Project
  1. Home
  2. General Programming
  3. C#
  4. How to interrupt a method in c#?

How to interrupt a method in c#?

Scheduled Pinned Locked Moved C#
csharpdata-structureshelptutorialquestion
9 Posts 4 Posters 0 Views 1 Watching
  • Oldest to Newest
  • Newest to Oldest
  • Most Votes
Reply
  • Reply as topic
Log in to reply
This topic has been deleted. Only users with topic management privileges can see it.
  • D Offline
    D Offline
    daniel abcde
    wrote on last edited by
    #1

    Hi, i'm writing a program about copy files from one place to other place. When the copy process start, it will shows up a form and tells user what file are being copied and there is a button to allow the user to stop the process. My problem is i cannot make the "stop" button works.The program code is like this: ======Copy Form====== private void StopButton_Click(object sender, EventArgs e) { frmTest.Stopcopying = true; return; } =======Main form(frmtest) ======================== .... public static bool Stopcopying = false; ... public static void copyDirectory(string Src, string Dst) { String[] Files; fmCopying.StartPosition.Equals("Center"); if (Dst[Dst.Length - 1] != Path.DirectorySeparatorChar) Dst += Path.DirectorySeparatorChar; if (!Directory.Exists(Dst)) Directory.CreateDirectory(Dst); Files = Directory.GetFileSystemEntries(Src); // int[] result = Array.FindAll(Files, delegate(int i){} frmCopying fmCopying1 = new frmCopying(); fmCopying1.Show(); foreach (string Element in Files) { fmCopying1.Refresh(); // Sub directories if (Directory.Exists(Element)){ if (frmTest.Stopcopying == true) { fmCopying1.Close(); return; } copyDirectory(Element, Dst + Path.GetFileName(Element)); fmCopying1.Refresh(); fmCopying1.lblCopying.Text =Element; fmCopying1.lblCopying2.Text = Dst + Path.GetFileName(Element); fmCopying1.Refresh(); } // Files in directory else { if (frmTest.Stopcopying == true) { fmCopying1.Close(); return; } File.Copy(Element, Dst + Path.GetFileName(Element), true); fmCopying1.Refresh(); fmCopying1.lblCopying.Text =Element; fmCopying1.lblCopying

    D 1 Reply Last reply
    0
    • D daniel abcde

      Hi, i'm writing a program about copy files from one place to other place. When the copy process start, it will shows up a form and tells user what file are being copied and there is a button to allow the user to stop the process. My problem is i cannot make the "stop" button works.The program code is like this: ======Copy Form====== private void StopButton_Click(object sender, EventArgs e) { frmTest.Stopcopying = true; return; } =======Main form(frmtest) ======================== .... public static bool Stopcopying = false; ... public static void copyDirectory(string Src, string Dst) { String[] Files; fmCopying.StartPosition.Equals("Center"); if (Dst[Dst.Length - 1] != Path.DirectorySeparatorChar) Dst += Path.DirectorySeparatorChar; if (!Directory.Exists(Dst)) Directory.CreateDirectory(Dst); Files = Directory.GetFileSystemEntries(Src); // int[] result = Array.FindAll(Files, delegate(int i){} frmCopying fmCopying1 = new frmCopying(); fmCopying1.Show(); foreach (string Element in Files) { fmCopying1.Refresh(); // Sub directories if (Directory.Exists(Element)){ if (frmTest.Stopcopying == true) { fmCopying1.Close(); return; } copyDirectory(Element, Dst + Path.GetFileName(Element)); fmCopying1.Refresh(); fmCopying1.lblCopying.Text =Element; fmCopying1.lblCopying2.Text = Dst + Path.GetFileName(Element); fmCopying1.Refresh(); } // Files in directory else { if (frmTest.Stopcopying == true) { fmCopying1.Close(); return; } File.Copy(Element, Dst + Path.GetFileName(Element), true); fmCopying1.Refresh(); fmCopying1.lblCopying.Text =Element; fmCopying1.lblCopying

      D Offline
      D Offline
      daniel abcde
      wrote on last edited by
      #2

      If i click on the stop button the window will freeze and the copy process don't stop.. My though in the code maynot be the best way of doing it, any ideas are welcome, many thanks for your help :)

      L 1 Reply Last reply
      0
      • D daniel abcde

        If i click on the stop button the window will freeze and the copy process don't stop.. My though in the code maynot be the best way of doing it, any ideas are welcome, many thanks for your help :)

        L Offline
        L Offline
        Luc Pattyn
        wrote on last edited by
        #3

        Hi, if you call the copyDirectory method on the GUI thread (say inside a button click handler, or a form load handler), then the GUI will be blocked as long as the copy takes, hence the stop button will not work during that time, making it useless. the right solution is to perform the copyDirectory on a separate thread, which gets launched by the start button or the form load handlers, and which does not run on the GUI thread, so you can move, resize, etc while the copy is going on; and you now can use the stop button. Warning: if you need to update the GUI (say show the filename currently being copied) you would need Control.InvokeRequired and Control.Invoke to do so. :)

        Luc Pattyn [Forum Guidelines] [My Articles]


        This month's tips: - before you ask a question here, search CodeProject, then Google; - the quality and detail of your question reflects on the effectiveness of the help you are likely to get; - use PRE tags to preserve formatting when showing multi-line code snippets.


        D 1 Reply Last reply
        0
        • L Luc Pattyn

          Hi, if you call the copyDirectory method on the GUI thread (say inside a button click handler, or a form load handler), then the GUI will be blocked as long as the copy takes, hence the stop button will not work during that time, making it useless. the right solution is to perform the copyDirectory on a separate thread, which gets launched by the start button or the form load handlers, and which does not run on the GUI thread, so you can move, resize, etc while the copy is going on; and you now can use the stop button. Warning: if you need to update the GUI (say show the filename currently being copied) you would need Control.InvokeRequired and Control.Invoke to do so. :)

          Luc Pattyn [Forum Guidelines] [My Articles]


          This month's tips: - before you ask a question here, search CodeProject, then Google; - the quality and detail of your question reflects on the effectiveness of the help you are likely to get; - use PRE tags to preserve formatting when showing multi-line code snippets.


          D Offline
          D Offline
          daniel abcde
          wrote on last edited by
          #4

          many thanks, Luc. I am now rewriting the Copy form and add Thread method to it, so when it starts it will open a new thread and start the copy method. But i don't quite get how to get Control.InvokeRequired and Control.Invoke works, can you please give a bit example or a bit explainlation of them? many thanks again! daniel

          Mircea PuiuM 1 Reply Last reply
          0
          • D daniel abcde

            many thanks, Luc. I am now rewriting the Copy form and add Thread method to it, so when it starts it will open a new thread and start the copy method. But i don't quite get how to get Control.InvokeRequired and Control.Invoke works, can you please give a bit example or a bit explainlation of them? many thanks again! daniel

            Mircea PuiuM Offline
            Mircea PuiuM Offline
            Mircea Puiu
            wrote on last edited by
            #5

            Use a delegate whenever you want to update controls created within other threads (i.e. to avoid cross-thread operations):

            delegate void SomeActionCallback( Control yourControl, ... other params here ... );
            void SomeAction( Control yourControl, ... other params here ... )
            {
            if (this.IsDisposed) return;
            if (yourControl.IsDisposed) return;
            if (yourControl.InvokeRequired)
            {
            SomeActionCallback deleg = new SomeActionCallback(SomeAction);
            this.Invoke(deleg, new object[] { yourControl, ... pass other params here ... });
            }
            else
            {
            // Set yourControl's properties here
            // .......
            }
            }

            Call SomeAction() whenever you want to update the controls of your form from a thread event handler.

            SkyWalker

            S 1 Reply Last reply
            0
            • Mircea PuiuM Mircea Puiu

              Use a delegate whenever you want to update controls created within other threads (i.e. to avoid cross-thread operations):

              delegate void SomeActionCallback( Control yourControl, ... other params here ... );
              void SomeAction( Control yourControl, ... other params here ... )
              {
              if (this.IsDisposed) return;
              if (yourControl.IsDisposed) return;
              if (yourControl.InvokeRequired)
              {
              SomeActionCallback deleg = new SomeActionCallback(SomeAction);
              this.Invoke(deleg, new object[] { yourControl, ... pass other params here ... });
              }
              else
              {
              // Set yourControl's properties here
              // .......
              }
              }

              Call SomeAction() whenever you want to update the controls of your form from a thread event handler.

              SkyWalker

              S Offline
              S Offline
              scott_hackett
              wrote on last edited by
              #6

              This is much easier when you use the BackgroundWorker class. It has thread marshalling built in, and makes it easy to get progress feedback and to allow mid-work cancelling. http://msdn2.microsoft.com/en-us/library/system.componentmodel.backgroundworker.aspx[^]

              Mircea PuiuM 1 Reply Last reply
              0
              • S scott_hackett

                This is much easier when you use the BackgroundWorker class. It has thread marshalling built in, and makes it easy to get progress feedback and to allow mid-work cancelling. http://msdn2.microsoft.com/en-us/library/system.componentmodel.backgroundworker.aspx[^]

                Mircea PuiuM Offline
                Mircea PuiuM Offline
                Mircea Puiu
                wrote on last edited by
                #7

                Yeah, but the "cros thread operation" is still there :-)

                SkyWalker

                D 1 Reply Last reply
                0
                • Mircea PuiuM Mircea Puiu

                  Yeah, but the "cros thread operation" is still there :-)

                  SkyWalker

                  D Offline
                  D Offline
                  daniel abcde
                  wrote on last edited by
                  #8

                  hi i have come accross a problem that after the process completed i cannot start the copy process again once it have completed. It complains "The object have been disposed", My question is how can i check if the bw have been stoped and i can start another bw(oR create a new bw)? I used the GUI to make the bw, it generates this private BackgroundWorker bw; ... this.bw = new System.ComponentModel.BackgroundWorker(); ... this.bw.DoWork += new System.ComponentModel.DoWorkEventHandler(this.bw_DoWork); this.bw.RunWorkerCompleted += new System.ComponentModel.RunWorkerCompletedEventHandler(this.bw_RunWorkerCompleted); ..... public static void copyDirectory(string Src, string Dst) // http://www.codeproject.com/KB/files/copydirectoriesrecursive.aspx { String[] Files; fmCopying.StartPosition.Equals("Center"); if (Dst[Dst.Length - 1] != Path.DirectorySeparatorChar) Dst += Path.DirectorySeparatorChar; if (!Directory.Exists(Dst)) Directory.CreateDirectory(Dst); Files = Directory.GetFileSystemEntries(Src); /* fmCopying.pBar1.Visible = true; // Set Minimum to 1 to represent the first file being copied. fmCopying.pBar1.Minimum = 1; // Set Maximum to the total number of files to copy. fmCopying.pBar1.Maximum = Files.Length; // Set the initial value of the ProgressBar. fmCopying.pBar1.Value = 2; // Set the Step property to a value of 1 to represent each file being copied. fmCopying.pBar1.Step = 1; */ foreach (string Element in Files) { fmCopying.Refresh(); // Sub directories if (Directory.Exists(Element)){ System.Threading.Thread.Sleep(1000); copyDirectory(Element, Dst + Path.GetFileName(Element)); fmCopying.Refresh(); fmCopying.lblCopying.Text =Element; fmCopying.lblCopying2.Text = Dst + Path.GetFileName(Element); fmCopying.Refresh(); } // Files in directory else { System.Threading.Thread.Sleep(1000); File.Copy(Element, Ds

                  Mircea PuiuM 1 Reply Last reply
                  0
                  • D daniel abcde

                    hi i have come accross a problem that after the process completed i cannot start the copy process again once it have completed. It complains "The object have been disposed", My question is how can i check if the bw have been stoped and i can start another bw(oR create a new bw)? I used the GUI to make the bw, it generates this private BackgroundWorker bw; ... this.bw = new System.ComponentModel.BackgroundWorker(); ... this.bw.DoWork += new System.ComponentModel.DoWorkEventHandler(this.bw_DoWork); this.bw.RunWorkerCompleted += new System.ComponentModel.RunWorkerCompletedEventHandler(this.bw_RunWorkerCompleted); ..... public static void copyDirectory(string Src, string Dst) // http://www.codeproject.com/KB/files/copydirectoriesrecursive.aspx { String[] Files; fmCopying.StartPosition.Equals("Center"); if (Dst[Dst.Length - 1] != Path.DirectorySeparatorChar) Dst += Path.DirectorySeparatorChar; if (!Directory.Exists(Dst)) Directory.CreateDirectory(Dst); Files = Directory.GetFileSystemEntries(Src); /* fmCopying.pBar1.Visible = true; // Set Minimum to 1 to represent the first file being copied. fmCopying.pBar1.Minimum = 1; // Set Maximum to the total number of files to copy. fmCopying.pBar1.Maximum = Files.Length; // Set the initial value of the ProgressBar. fmCopying.pBar1.Value = 2; // Set the Step property to a value of 1 to represent each file being copied. fmCopying.pBar1.Step = 1; */ foreach (string Element in Files) { fmCopying.Refresh(); // Sub directories if (Directory.Exists(Element)){ System.Threading.Thread.Sleep(1000); copyDirectory(Element, Dst + Path.GetFileName(Element)); fmCopying.Refresh(); fmCopying.lblCopying.Text =Element; fmCopying.lblCopying2.Text = Dst + Path.GetFileName(Element); fmCopying.Refresh(); } // Files in directory else { System.Threading.Thread.Sleep(1000); File.Copy(Element, Ds

                    Mircea PuiuM Offline
                    Mircea PuiuM Offline
                    Mircea Puiu
                    wrote on last edited by
                    #9

                    You can find a lot of coding examples on the net. This[^] is one of them.

                    SkyWalker

                    1 Reply Last reply
                    0
                    Reply
                    • Reply as topic
                    Log in to reply
                    • Oldest to Newest
                    • Newest to Oldest
                    • Most Votes


                    • Login

                    • Don't have an account? Register

                    • Login or register to search.
                    • First post
                      Last post
                    0
                    • Categories
                    • Recent
                    • Tags
                    • Popular
                    • World
                    • Users
                    • Groups