ContextSwitchDeadlock was detected - CLR unable to switch contexts

I'm using VS Express (VB) and have a Windows form that uses the My.Computer.FileSystem.GetDirectories to get a list of files in a directory and then using the My.Computer.FileSystem.CopyFile to copy the files in the directory to a new location. As each file is copied I'm updating a ListBox (adding an item). After about 2-3 files the ListBox is no longer updated (even tried Refreshing the ListBox and/or Form) and if there are very many files I get the ContextSwitchDeadlock error but I can hit continue and the process will finish. Only after all of the files are copied and the process is complete does the ListBox show all of the added items. How can I get the ListBox to update after each file copy and how can I prevent the ContextSwitchDeadlock error

Answer this question

ContextSwitchDeadlock was detected - CLR unable to switch contexts

  • Andrei Romanenko

    Wow this is the second time today I've answered this.

    You are in loops and compute bound. Nothing else is getting any CPU to maintain connections (assuming you are not in an infinite loop where this is also true.

    Every once in while your process needs to let go of it's compute resources to allow other threads to execute and to allow your machine to do it's normal housekeeping.

    in an outer loop add

    Application.DoEvents

    This should take care of your problem.



  • e6matt

    same here.... been trying to find what API I would call to prevent this....

    I forgot about the good old Application.DoEvents() of Visual Basic 6.....

    thanks so much....

  • Agent-Smith

    You're welcome!



  • popsmike

    That did it. I've been trying to figure this out for days. I knew it was the long process causing the problem, I just didn't know how to prevent it. The only thing that I found that worked was putting in a MsgBox every once in a while - which of course wouldn't work for a real app.

    You're the Best!!! Thanks a bunch!


  • ContextSwitchDeadlock was detected - CLR unable to switch contexts