VB.NET Listview ContextSwitchDeadlock Was Detected

Refer to previous post on VB.NET Listview Slow.

If you happen to get this error ('ContextSwitchDeadlock Was Detected') while displaying items to a ListView component.

'Message: The CLR has been unable to transition from COM context 0x5228fe8 to COM context 0x5229158 for 60 seconds. The thread that owns the destination context/apartment is most likely either doing a non pumping wait or processing a very long running operation without pumping Windows messages. This situation generally has a negative performance impact and may even lead to the application becoming non responsive or memory usage accumulating continually over time. To avoid this problem, all single threaded apartment (STA) threads should use pumping wait primitives (such as CoWaitForMultipleHandles? ) and routinely pump messages during long running operations.'



This is caused by a process such as 'lv.Items.AddRange(lvItems)' is taking too long to finish and thus the process timeout. It doesn't happen all the time, but if your CPU utilization is high, very high possibility you will get this error.

Refer to the sample code (VB.NET Visual Studio 2008 SP1), you can see that in Form8 and Form9, the delay in displaying items is caused by codes in the 'ListView.ItemChecked' event; which may or may not bring about 'ContextSwitchDeadlock Was Detected' error. The reason is that 'ItemChecked' event is being called every time a ListViewItem is added to the ListView.

The solution is to dynamically add and remove handler to 'ListView.ItemChecked'. Refer to Form10.


Comments