0

I have a heavy function that uses a lot of regular expressions to match a big test into rich text box.

Every time that this text is changed ( OnTextChangedEvent ) is called this function. This function if I write quickly paralyzes the entire program for a while.

I thought about some solution such as:

  • Delay on event changed
  • Thread
  • Run this function on idle cycle.

Which is the best? And how can I apply this to my function?

mghie
  • 32,028
  • 6
  • 87
  • 129

3 Answers3

1

A function like this should not be called from OnTextChanged. Make it run in a background thread, update the results when it completes. Think of how Intellisense works--it's triggered by any change to the code but only updates the screen when it's got answers.

Loren Pechtel
  • 8,945
  • 3
  • 33
  • 45
0

I agree with Loren's answer, but here's some more info/options.

First, the heavy reg ex should be run on a different thread, not the one with your GUI. On your OnTextChanged, set a global dirty bit and a timestamp (for example, :dirty @ 20:00).

Your background thread can pick this up, and run happily ever after in the background, until it finishes, and updates the GUI. Once it's done, it can check to see if there are any dirty bits that came after it started, or since last finished.

An even better approach might be to cancel it's running calculation if the changes invalidate what it's doing, but you didn't supply enough data for that.

Noctis
  • 11,507
  • 3
  • 43
  • 82
  • A quibble here--I wouldn't have a dirty bit. Rather, I would simply store the timestamp of the last modification. If the timestamp of the last calculation doesn't match you need to run it again. – Loren Pechtel Jun 16 '14 at 02:28
  • @LorenPechtel technically correct. if you have the last modification you can check to see if it's later, but I prefer code that reads: `if (dirty) ...` over `if (timestamp > last_timestamp)`, even though you could just write a helper method called `dirty` that will do it for you. Same same. – Noctis Jun 16 '14 at 04:57
  • I wouldn't mind the dirty() function. I would mind having two variables that basically do the same thing. – Loren Pechtel Jun 16 '14 at 16:56
0

You are asking for an opinion. My view is that this problem is best solved by running it on a separate thread.

In the past we would have done it on the idle loop, but there really is no advantage and quite a bit of pain. The idle loop is still a reasonable way to do things that must continuously update the UI, but otherwise not worth the hassle.

You other suggestion leads nowhere.

But that's just my opinion.

david.pfx
  • 10,520
  • 3
  • 30
  • 63