简体   繁体   中英

Call function in aspx.cs page from global.asax

i got code inglobal.asax page:

void Application_Start(object sender, EventArgs e) 
{
    // Code that runs on application startup
    System.Timers.Timer timScheduledTask = new System.Timers.Timer();

    // Timer interval is set in miliseconds,
    // In this case, we'll run a task every minute
    timScheduledTask.Interval = 60 * 1000;

    timScheduledTask.Enabled = true;

    // Add handler for Elapsed event
    timScheduledTask.Elapsed += new System.Timers.ElapsedEventHandler(timScheduledTask_Elapsed);
}

void timScheduledTask_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
{
    // Over here i want to call  function that i have in asp.net page 
}

my problem here that in timScheduledTask_Elapsed function, i want to call to function that i have in asp.net page (Contacts.aspx.cs).

Any idea how to call this function??

It would need to be a static method of the page as the application class has no way of knowing the current page instance.

A rough example can be seen below.

somepage.aspx:

public class SomePage : Page
{

    public static void DoSomething()
    {
        ...
    }

}

global.asax:

void Application_Start(object sender, EventArgs e) 
{
    ...

    // Add handler for Elapsed event
    timScheduledTask.Elapsed += new System.Timers.ElapsedEventHandler(timScheduledTask_Elapsed);


}

void timScheduledTask_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
{
    SomePage.DoSomething(); 
}

However, this does mean that anything in DoSomething() must not rely on anything instance specific in the page.

I would rethink your approach.

Also note that timers are a bad idea here IMHO, if the application process unloads your timers will never get called so you cannot really rely on them.

If you need to call a PAGE method from outside, you have a very bad design. Before doing anything else I'd advise you to do some research on separating your code into multiple layers, so such situation can never happen.

If you however still insist you want to do it your way (you'll understand sooner or later anyway), simplest solution is to make the requested page method static. That way you can call it anytime without a reference to an actual instance.

I'd make the code into a non-visual class and call it.

If you need it to be visual, make it a visual user control and include it on a master page that you use.

I agree that trying to call something on a different page when that's not the page running is just asking for problems.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM