0

If I start a System.Threading.Timerin a currently executing method, the method will continue to execute and return to the main method and the Timer.Tick event will fire sometime in the immediate future (based on the timer's duration). For my purpose, I need something like a timer, but the duration would be calculated on the time it takes to finish executing the current method, i.e. the Tick executes directly after the current method returns.

Is there a way to 'schedule' a method to begin immediately after the current method executes before returning to the main method?

EDIT: Here's the issue I have that I am trying to work around.

A System.Windows.Controls.TreeviewItem contains an event TreeviewItem.Collapsed, which is internally invoked before layout, as we can see here in the OnIsExpandedChanged method that item.UpdateVisualState() is called after invoking the event. I therefore cannot use the updated layout to reposition my controls. IMO the event should be called OnCollapsing or BeginCollapsed.

I needed the collapsing to finish executing and then give me a chance to work with the new state.

NWoodsman
  • 423
  • 4
  • 10
  • Maybe use a [BackgroundWorker](https://stackoverflow.com/questions/6481304/how-to-use-a-backgroundworker). Once it finishes, you can run a task. – Tronald Mar 02 '18 at 22:11
  • Can you start the timer on the last line of the method? That seems to meet the criteria listed unless you need it to keep firing at the same interval (where you wanted it started and the end of the method). – David Dowdle Mar 02 '18 at 22:11
  • Hard to understand your requirements, maybe try listing a sample sequence? – Richard Padre Mar 02 '18 at 22:18
  • It really would help if you explained what you are trying to accomplish, not what [you are trying to do](https://meta.stackexchange.com/questions/66377/). – Dour High Arch Mar 02 '18 at 22:37
  • @DourHighArch added the rationale. – NWoodsman Mar 03 '18 at 00:30

1 Answers1

0

No, there is no way to create/schedule callback that can be inserted "directly after the current method returns". Ability to do so would require modification of call stack at run-time which generally is not exposed by any runtimes.

There are likely other ways to implement actual feature you may be looking for. I.e. measuring time for methods can be done with auto-generated wrappers for interfaces similar how Unity interceptors work.

Alexei Levenkov
  • 98,904
  • 14
  • 127
  • 179