user300981
user300981

Reputation: 1433

Fire a method execution after x seconds in code behind - ASP.NET/C#

After x seconds, after the page loads, I need to execute a method in the code behind. I cannot move this logic into JS.

Do I need to use delegates/events for this? Can anyone give me an example (preferably with a code snippet)??

Upvotes: 2

Views: 1081

Answers (2)

Mitchel Sellers
Mitchel Sellers

Reputation: 63136

Your best solution is going to be to use javascript to either cause a postback, or to send an AJAX request to the server after the X seconds has elapsed.

Due to the page lifecycle of ASP.NET pages, you can't do it from the code-behind directly. You can see this article for more information on the ASP.NET Page Lifecycle.

I would put a bit of javascript that uses the "SetTimeout" to trigger a JS method call that either does the Ajax request, or forces the postback, depending on what you are doing.

Edit

Based on the additional information you put in the comments to the post i would recommend a modified approach. If all you are doing is launching another window, and you want to delay that logic.

Instead of directly calling the window.open or however you are doing it. Simply put that code inside of the code that would be called using the "SetTimeout" method as I referred to earlier. No need to involve the server-side at all.

Upvotes: 2

Caladain
Caladain

Reputation: 4934

Put a counter in JS that measures the X seconds. Once it's reached it's mark, have it send a message via AJAX back to the server, and the server executes the method.

That's about the only way to ensure that the counting of those seconds is accurate to when the page finishes loading. If you don't care too much about accuracy, just have the server kick off the method x seconds after it sends the page.

Upvotes: 3

Related Questions