Results 1 to 19 of 19

Thread: [RESOLVED] Commands executing in wrong order?

  1. #1

    Thread Starter
    New Member
    Join Date
    Apr 2013
    Posts
    14

    Resolved [RESOLVED] Commands executing in wrong order?

    For the below code, the program starts copying file in the CopyFiles() Function before it does Label11.Visible = True or Button1.Enabled = False. Anyone know why? I did try putting in a System.Threading.Thread.Sleep(3000) command as well, but that didn't work either.

    Code:
        Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
            Label11.Visible = True
            Button1.Enabled = False
            ' System.Threading.Thread.Sleep(3000)
            CopyFiles()
            Button1.Visible = False
        End Sub
    Any help would be appreciated!

  2. #2
    PowerPoster dunfiddlin's Avatar
    Join Date
    Jun 2012
    Posts
    8,245

    Re: Commands executing in wrong order?

    No it doesn't. CopyFiles() starts before the results of the two commands can be painted on the form and then hogs the UI preventing it being completed. Putting a sleep in there makes no difference because it simply stops all events. It looks like copyfiles could do with being on a separate thread or a background worker but in the meantime try putting in ...

    Application.DoEvents()

    ... after Button1.Enabled = False and before CopyFiles(). In theory at least that should complete the events relating to the painting of the controls before continuing.
    As the 6-dimensional mathematics professor said to the brain surgeon, "It ain't Rocket Science!"

    Reviews: "dunfiddlin likes his DataTables" - jmcilhinney

    Please be aware that whilst I will read private messages (one day!) I am unlikely to reply to anything that does not contain offers of cash, fame or marriage!

  3. #3
    PowerPoster techgnome's Avatar
    Join Date
    May 2002
    Posts
    34,687

    Re: Commands executing in wrong order?

    It's because UI updates are a low priority... I'd probably reach for a Me.Refresh before going for the jugular with the DoEvents... but that's probably just me.

    -tg
    * I don't respond to private (PM) requests for help. It's not conducive to the general learning of others.*
    * I also don't respond to friend requests. Save a few bits and don't bother. I'll just end up rejecting anyways.*
    * How to get EFFECTIVE help: The Hitchhiker's Guide to Getting Help at VBF - Removing eels from your hovercraft *
    * How to Use Parameters * Create Disconnected ADO Recordset Clones * Set your VB6 ActiveX Compatibility * Get rid of those pesky VB Line Numbers * I swear I saved my data, where'd it run off to??? *

  4. #4
    PowerPoster dunfiddlin's Avatar
    Join Date
    Jun 2012
    Posts
    8,245

    Re: Commands executing in wrong order?

    You raise an interesting point, Moriarty! We shall duel over it tomorrow at dawn (well, somewhere it'll be dawn!) but for now it's high time I was tucked up in bed!
    As the 6-dimensional mathematics professor said to the brain surgeon, "It ain't Rocket Science!"

    Reviews: "dunfiddlin likes his DataTables" - jmcilhinney

    Please be aware that whilst I will read private messages (one day!) I am unlikely to reply to anything that does not contain offers of cash, fame or marriage!

  5. #5
    Angel of Code Niya's Avatar
    Join Date
    Nov 2011
    Posts
    9,017

    Re: Commands executing in wrong order?

    A refresh would probably be preferable. DoEvents is just.....evil!!!
    Treeview with NodeAdded/NodesRemoved events | BlinkLabel control | Calculate Permutations | Object Enums | ComboBox with centered items | .Net Internals article(not mine) | Wizard Control | Understanding Multi-Threading | Simple file compression | Demon Arena

    Copy/move files using Windows Shell | I'm not wanted

    C++ programmers will dismiss you as a cretinous simpleton for your inability to keep track of pointers chained 6 levels deep and Java programmers will pillory you for buying into the evils of Microsoft. Meanwhile C# programmers will get paid just a little bit more than you for writing exactly the same code and VB6 programmers will continue to whitter on about "footprints". - FunkyDexter

    There's just no reason to use garbage like InputBox. - jmcilhinney

    The threads I start are Niya and Olaf free zones. No arguing about the benefits of VB6 over .NET here please. Happiness must reign. - yereverluvinuncleber

  6. #6
    PowerPoster techgnome's Avatar
    Join Date
    May 2002
    Posts
    34,687

    Re: Commands executing in wrong order?

    I wouldn't call it "Evil" ... it's jsut misunderstood and oft abused.

    -tg
    * I don't respond to private (PM) requests for help. It's not conducive to the general learning of others.*
    * I also don't respond to friend requests. Save a few bits and don't bother. I'll just end up rejecting anyways.*
    * How to get EFFECTIVE help: The Hitchhiker's Guide to Getting Help at VBF - Removing eels from your hovercraft *
    * How to Use Parameters * Create Disconnected ADO Recordset Clones * Set your VB6 ActiveX Compatibility * Get rid of those pesky VB Line Numbers * I swear I saved my data, where'd it run off to??? *

  7. #7
    Hyperactive Member
    Join Date
    Apr 2010
    Posts
    420

    Re: Commands executing in wrong order?

    For the ones that are not quite advanced with vb as others, what's wrong with DoEvents ?

  8. #8
    Powered By Medtronic dbasnett's Avatar
    Join Date
    Dec 2007
    Location
    Jefferson City, MO
    Posts
    9,897

    Re: Commands executing in wrong order?

    Quote Originally Posted by techgnome View Post
    It's because UI updates are a low priority... I'd probably reach for a Me.Refresh before going for the jugular with the DoEvents... but that's probably just me.

    -tg
    And me. If the user want to process all messages in the message queue then by all means use DoEvents. If the user wants to repaint the screen then Me.Refresh is suitable. You can put screws in wood with a hammer, but the side effects...

    The DoEvents route is just a very bad habit to get into.
    My First Computer -- Documentation Link (RT?M) -- Using the Debugger -- Prime Number Sieve
    Counting Bits -- Subnet Calculator -- UI Guidelines -- >> SerialPort Answer <<

    "Those who use Application.DoEvents have no idea what it does and those who know what it does never use it." John Wein

  9. #9
    Powered By Medtronic dbasnett's Avatar
    Join Date
    Dec 2007
    Location
    Jefferson City, MO
    Posts
    9,897

    Re: Commands executing in wrong order?

    Quote Originally Posted by Signalman View Post
    For the ones that are not quite advanced with vb as others, what's wrong with DoEvents ?
    Nothing, so long as you understand EXACTLY what it does (see DoEvents).

    Add a button and label to a new form. Put this code in the Button Click

    Code:
            Dim i As Integer = 0
            Static li As Integer
            li = 0
            Do While i <> 5000
                i += 1
                Label1.Text = i.ToString
    
                If li + 1 <> i Then Stop 'does it stop here? Why?
    
                li = i
    
                'uncomment one of the following
                'Label1.Refresh()
                'Application.DoEvents()
            Loop
    un-comment the label1.refresh statement and run the program. Click the button. When you see the label start to count up Click it again.

    Then comment out the label1.refresh statement, and un-comment the DoEvents and run the program again. Click the button. When you see the label start to count up Click it again.

    Notice the difference? Do you understand why?

    With the label un-commented you will see the count increment by 1 until it reaches 5000 for each click. With DoEvents un-commented you will see the count increment by 1 until the button is clicked.

    The bugs that can be created with DoEvents are subtle and often hard to find. My opinion about DoEvents is in my signature.
    Last edited by dbasnett; May 4th, 2013 at 08:58 AM.
    My First Computer -- Documentation Link (RT?M) -- Using the Debugger -- Prime Number Sieve
    Counting Bits -- Subnet Calculator -- UI Guidelines -- >> SerialPort Answer <<

    "Those who use Application.DoEvents have no idea what it does and those who know what it does never use it." John Wein

  10. #10
    PowerPoster dunfiddlin's Avatar
    Join Date
    Jun 2012
    Posts
    8,245

    Re: Commands executing in wrong order?

    Geez guys. Calm down. Nobody was suggesting putting it in a loop! Just a one off, clear the decks before the big, nasty, hogging procedure begins.
    As the 6-dimensional mathematics professor said to the brain surgeon, "It ain't Rocket Science!"

    Reviews: "dunfiddlin likes his DataTables" - jmcilhinney

    Please be aware that whilst I will read private messages (one day!) I am unlikely to reply to anything that does not contain offers of cash, fame or marriage!

  11. #11
    Angel of Code Niya's Avatar
    Join Date
    Nov 2011
    Posts
    9,017

    Re: Commands executing in wrong order?

    Quote Originally Posted by Signalman View Post
    For the ones that are not quite advanced with vb as others, what's wrong with DoEvents ?
    Oh God I can write a book...I once wrote an app to do file transfers via TCP/IP in VB6. Now anyone who has any experience with network coding would tell you that threading is essential to making a quality network application. Only problem....VB6 doesn't allow multi-threading so the next best thing was DoEvents. The reetrancy problems I encountered caused so many problems, I was practically getting gray. While I eventually got it to work, it became one huge tangled mess of a program. What would have otherwise been an elegant application was such a butchered mess that even to this day I fear going near the source code. Just looking at the code gives me a headache.

    I've learned the hard way just how malignant DoEvents can really be. Its ease of use gives you such a false sense of security. The problem with it is that you can easily forget that a single threaded application only has a single execution path. If you don't account for reetrancy, you can end up with one twisted call stack several levels deep which can place your program is such exceptional states that you can hardly account for all of them. And good luck trying to fix bugs cause by these conditions. I'm am telling you, DoEvents should have stayed in VB6 where it was a necessary evil.
    Treeview with NodeAdded/NodesRemoved events | BlinkLabel control | Calculate Permutations | Object Enums | ComboBox with centered items | .Net Internals article(not mine) | Wizard Control | Understanding Multi-Threading | Simple file compression | Demon Arena

    Copy/move files using Windows Shell | I'm not wanted

    C++ programmers will dismiss you as a cretinous simpleton for your inability to keep track of pointers chained 6 levels deep and Java programmers will pillory you for buying into the evils of Microsoft. Meanwhile C# programmers will get paid just a little bit more than you for writing exactly the same code and VB6 programmers will continue to whitter on about "footprints". - FunkyDexter

    There's just no reason to use garbage like InputBox. - jmcilhinney

    The threads I start are Niya and Olaf free zones. No arguing about the benefits of VB6 over .NET here please. Happiness must reign. - yereverluvinuncleber

  12. #12
    Powered By Medtronic dbasnett's Avatar
    Join Date
    Dec 2007
    Location
    Jefferson City, MO
    Posts
    9,897

    Re: Commands executing in wrong order?

    Quote Originally Posted by dunfiddlin View Post
    Geez guys. Calm down. Nobody was suggesting putting it in a loop! Just a one off, clear the decks before the big, nasty, hogging procedure begins.
    DoEvents is (almost) never the answer, and suggesting to an inexperienced user that it is the answer is a recipe for disaster down the road. You pointed out what the user needed to accomplish, "painting of the controls before continuing", so isn't the direct approach to that Me.Refresh? If I had an integer variable named x and wanted to increment it by 1 would you suggest x = x + (&HFFFE Xor &HFFFF)?
    My First Computer -- Documentation Link (RT?M) -- Using the Debugger -- Prime Number Sieve
    Counting Bits -- Subnet Calculator -- UI Guidelines -- >> SerialPort Answer <<

    "Those who use Application.DoEvents have no idea what it does and those who know what it does never use it." John Wein

  13. #13
    PowerPoster dunfiddlin's Avatar
    Join Date
    Jun 2012
    Posts
    8,245

    Re: Commands executing in wrong order?

    "painting of the controls before continuing", so isn't the direct approach to that Me.Refresh?
    It may be the direct approach but it doesn't work in this context. In so far as I was able to replicate the problem, in several scenarios it had no effect whatsoever. As far as I can see it does no more than duplicate the repaint process that's already in hand as a result of the change of style/text and worse also requires a repaint of all the other controls on the form and the form itself. I don't see how adding a whole new set of events to the queue is meant to solve the traffic jam that already exists. So if it's the answer I'm pretty sure we've got the wrong question!

    In fact I did not suggest DoEvents as The Answer only as something worth trying if the OP was unable to commit to The Answer I actually proposed; threading of the Copy() process. But let's not let the facts get in the way of a good argument!
    As the 6-dimensional mathematics professor said to the brain surgeon, "It ain't Rocket Science!"

    Reviews: "dunfiddlin likes his DataTables" - jmcilhinney

    Please be aware that whilst I will read private messages (one day!) I am unlikely to reply to anything that does not contain offers of cash, fame or marriage!

  14. #14
    Powered By Medtronic dbasnett's Avatar
    Join Date
    Dec 2007
    Location
    Jefferson City, MO
    Posts
    9,897

    Re: Commands executing in wrong order?

    Quote Originally Posted by dunfiddlin View Post
    It may be the direct approach but it doesn't work in this context. In so far as I was able to replicate the problem, in several scenarios it had no effect whatsoever. As far as I can see it does no more than duplicate the repaint process that's already in hand as a result of the change of style/text and worse also requires a repaint of all the other controls on the form and the form itself. I don't see how adding a whole new set of events to the queue is meant to solve the traffic jam that already exists. So if it's the answer I'm pretty sure we've got the wrong question!

    In fact I did not suggest DoEvents as The Answer only as something worth trying if the OP was unable to commit to The Answer I actually proposed; threading of the Copy() process. But let's not let the facts get in the way of a good argument!
    It would be interesting to see what you tried that Me.Refresh didn't work. The suggestion to use Refresh was in contrast to DoEvents. The OP only needed to Refresh the specific controls.

    What concerned me, and maybe others, was that the OP probably did "try" DoEvents and achieved the desired result. From what I can tell the OP hasn't had much to say on this thread. If they did follow this advice, "in the meantime try putting in ...Application.DoEvents()" they may think it is the answer to all similar problems, whether or not that was your intent. Most people here don't advocate the use of DoEvents because of the potential problems it can create.

    It surprised me that you suggested it.
    My First Computer -- Documentation Link (RT?M) -- Using the Debugger -- Prime Number Sieve
    Counting Bits -- Subnet Calculator -- UI Guidelines -- >> SerialPort Answer <<

    "Those who use Application.DoEvents have no idea what it does and those who know what it does never use it." John Wein

  15. #15

    Thread Starter
    New Member
    Join Date
    Apr 2013
    Posts
    14

    Re: [RESOLVED] Commands executing in wrong order?

    Thank you for the examlpes / explanations Niya! Marking thread as resolved and using the Me.Refresh() command works great!

  16. #16
    Super Moderator Shaggy Hiker's Avatar
    Join Date
    Aug 2002
    Location
    Idaho
    Posts
    40,104

    Re: [RESOLVED] Commands executing in wrong order?

    There are situations where .Refresh doesn't appear to work. I used that in a tight loop where I was updating a label with a counter. Whatever else was happening in that loop was super fast. The label updated for a time, but inevitably it would eventually stop updating. I didn't care, so I didn't bother trying to figure out why.

    Still, if you call .Refresh, do it as narrowly as you can. For example, just refresh the specific controls that need to be painted rather than refreshing the whole form. The difference matters when the loop is tight.
    My usual boring signature: Nothing

  17. #17
    I'm about to be a PowerPoster! Joacim Andersson's Avatar
    Join Date
    Jan 1999
    Location
    Sweden
    Posts
    14,649

    Re: Commands executing in wrong order?

    Quote Originally Posted by Niya View Post
    Now anyone who has any experience with network coding would tell you that threading is essential to making a quality network application.
    That's not true. Anyone that has any experience with network coding would tell you that asynchronous code is essential to making quality network applications. Threading is about concurrency for CPU intensive code, network accessing is not CPU intensive at all since most of the time the CPU will just sit and wait for the IO request to finish.

    There's a difference between concurrency and asynchronous code, unless you're still running your application on a single core CPU computer (and who does that today?).

  18. #18
    Angel of Code Niya's Avatar
    Join Date
    Nov 2011
    Posts
    9,017

    Re: Commands executing in wrong order?

    Quote Originally Posted by Joacim Andersson View Post
    That's not true. Anyone that has any experience with network coding would tell you that asynchronous code is essential to making quality network applications. Threading is about concurrency for CPU intensive code, network accessing is not CPU intensive at all since most of the time the CPU will just sit and wait for the IO request to finish.

    There's a difference between concurrency and asynchronous code, unless you're still running your application on a single core CPU computer (and who does that today?).
    Actually, yes you're right. I often forget there's a distinction between asynchronous code and threaded code. The .Net framework implements many asynchronous methods using threading so I'm used to thinking of the two concepts as the same thing.
    Treeview with NodeAdded/NodesRemoved events | BlinkLabel control | Calculate Permutations | Object Enums | ComboBox with centered items | .Net Internals article(not mine) | Wizard Control | Understanding Multi-Threading | Simple file compression | Demon Arena

    Copy/move files using Windows Shell | I'm not wanted

    C++ programmers will dismiss you as a cretinous simpleton for your inability to keep track of pointers chained 6 levels deep and Java programmers will pillory you for buying into the evils of Microsoft. Meanwhile C# programmers will get paid just a little bit more than you for writing exactly the same code and VB6 programmers will continue to whitter on about "footprints". - FunkyDexter

    There's just no reason to use garbage like InputBox. - jmcilhinney

    The threads I start are Niya and Olaf free zones. No arguing about the benefits of VB6 over .NET here please. Happiness must reign. - yereverluvinuncleber

  19. #19
    I'm about to be a PowerPoster! Joacim Andersson's Avatar
    Join Date
    Jan 1999
    Location
    Sweden
    Posts
    14,649

    Re: [RESOLVED] Commands executing in wrong order?

    Well, you're excused since those are two concept that many people mix together, and the main reason for that is simply because back when we only had one CPU core in our PCs there was no difference between the two concepts. Asynchronous calls can, as you mentioned, be implemented using threads but doesn't have to be, and in many cases there is no need to spin things off to a second thread on a second CPU core since the bulk work is really handled by some other hardware (when we talk about IO work, such as networking).

    The rule of thumb is: Use concurrency (threading) when you have CPU intensive code and use asynchronous calls for intensive IO work. Most applications use intensive IO work (networking, database queries, disk file management and so on) in a far higher degree than they use CPU intensive code (pure number crushing).

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width