-1

I have child form that has a TextReader to load some values on being called. It keeps crashing the moment I summon the form. This form has a Timer that updates the text of a TextBox this way:

textbox.Text = this.ActiveControl.Name;

I notice that disabling the timer during the loading operation stops the crashing from happening. Am I right to say that the TextReader is interfered by this.ActiveControl and causes the crash?

The VS Just-in-Timer debugger gives out differe [xxxx] error code each time. Trying to debug with VS gets "Unable to attach crashing process. A debugger is already attached."

CaTx
  • 1,421
  • 4
  • 21
  • 42

2 Answers2

1

It is likely that you have a race condition: if the ActiveControl is not yet initialized when the timer is called (and tries to access it), you will get a crash. As you mentioned you need to ensure that the timer does not access the invalid ActiveControl until it is fully intialized (by either disabling it until then or protecting the access by some other means (e.g. mutex/semaphore))

Attila
  • 28,265
  • 3
  • 46
  • 55
  • Attila, I think you are right. Inside Form_Load(), I disable the Timer before calling the TextReader() method, then re-enable it after it is done. No more crash. Previously, I did the same thing but inside my TextReader() method. I am new to C#, so stuffs like 'race condition' and what not are pretty new to me. – CaTx Jun 18 '12 at 17:27
  • @hoangnguyen - race conditionnnsre not unique to C# -- you will have to deal with them for any environment where simulateous execution is possible (e.g. threads). The form initialization and the timer runs in separate threads so you have to be careful how to orchestrate access to the same things between the two – Attila Jun 18 '12 at 17:31
0

Thank you everyone for your help. I overlooked Hans Passant's reply. Now when I nest my TextBox text update inside an if this way:

if (this.ActiveControl != null) { tbTest.Text = this.ActiveControl.Name; }

no more crashing occurs, even if I do not disable the timer. Kaboom, Hans nailed the error! ^^

Thanks to Attila for giving me the pointer to race condition. Very useful in the knowledge toolbox.

CaTx
  • 1,421
  • 4
  • 21
  • 42
  • I guess Timer_Tick() is a close (but not) answer. The form crashes when ActiveControl is null, but my code tries to pull the Name from it. So disabling timer gives the code some time to assign an ActiveControl. – CaTx Jun 18 '12 at 17:48