2

I need a run-only-once method that when all the criteria are met, say A&B&C are true, run the codes once, but only once. So if later on all the criteria are met again (A&B&C are true again but I don't care then), the code won't be run again.

This is not to solve the multithread issue, there is no data synchronization problem here, just later on all the criteria may be met again.

I have tried a method like this: add another property, update it when some criterion is met. When all the criteria are met, run the code, then set it to a special value, which will prevent it from running again.

For example, set its initial value to 1, when A is true &2, when B is true &4, when C is true & 8, so when it is 15, run the codes and set its value to 0. so later on, it will never be 15 again.

I was wondering if there a better way?

  • 1
    Do not use the values of your operands to signal program state. Use a class level property instead. Be wary of "magic values", they hardly ever serve you right. – Martin Maat Mar 3 '17 at 6:21
  • I agree that in general. But in my particular case, surely I can define an enum for them, but I don't see much value added here. Set it to 0 serve the purpose of running it just once. – Qiulang Mar 3 '17 at 6:29
4

Looks like you're going to need another variable as a trigger that can be tested against when then method is called. Make it something easy to remember like hasRun=false. When the method is first run you can change the value of it to true.

|improve this answer|||||

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.