Friday, February 5, 2016

Red X, Micrsoft Chart control drawing exception "Collection was modified; enumeration operation may not execute"



Microsoft Chart Control: What a Silly Exception!



Hey, most of developers who use Microsoft chart control will face that message and Red X message.

Case
It is required in some application that it draws charts and this chart is dynamically refreshed based on schedule, For example, chart is drawing latency rate for restaurant latency service, this chart will be motioned every time, to get the new calculation after new entered customer.

Cause
Simply, the root cause of this exception is that data source of chart is modified by background thread, while chart self is drawn by main thread. OnPaint (main method for painting for windows form) can't handle this exception and so it raise this exception and draw nothing

The following code will raise the exception


















As you see, the method doTask is called from background thread, that is responsible to draw charts based on data sourced changed every one minuter.



Solution
.Net framework provide property to check if invoke for thread is required or not, if required, so all what you need to to invoke method directly through delegate

The below correct the situation



Regards
Hany Mohamed