How to run Background process in ASP.Net web Appli

2019-04-01 01:15发布

问题:

I want to execute some of the function in my web application without intimating the user about the running process just like background process in windows application.

I want to trigger background process when user click and want to send some data to these function too.

Can any one suggest me how this could be performed?

回答1:

private readonly BackgroundWorker backgroundWorker1 = new BackgroundWorker();

protected void Page_Load(object sender, EventArgs e)
    {
        this.backgroundWorker1.DoWork += new System.ComponentModel.DoWorkEventHandler(this.backgroundWorker1_DoWork);
    }

    private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
    {
        try
        {
            timing();
        }
        catch
        {
        }
    }

    public void timing()
    {
        string tt = DateTime.Now.ToString("tt");
        string t = "";
        if (tt == "AM")
        {
            int hour = DateTime.Now.Hour;
            if ((hour >= 0) & (hour <= 11))
            {
                t = "GOOD MORNING";
            }
        }
        else if (tt == "PM")
        {
            int hour = DateTime.Now.Hour;
            if ((hour >= 12) & (hour <= 15))
            {
                t = "GOOD AFTERNOON";
            }
            else if ((hour >= 16) & (hour <= 23))
            {
                t = "GOOD EVENING";
            }
        }
        Label1.Text = t;
    }
    protected void Button1_Click(object sender, EventArgs e)
    {
        backgroundWorker1.RunWorkerAsync();
    }


//SOURCE:

<%@ Page Language="C#" Async="true" AutoEventWireup="true" CodeFile="background.aspx.cs" Inherits="background" %> //Async="true"


回答2:

Maybe you can follow these links and get an idea about how to approach the requirement.

http://www.dotnetfunda.com/articles/article613-background-processes-in-asp-net-web-applications.aspx

http://blog.stackoverflow.com/2008/07/easy-background-tasks-in-aspnet/

http://www.codeproject.com/Questions/137330/Run-a-background-job-in-ASP-NET



回答3:

Though it solves a more complex problem (how to do this when using IoC where object lifetimes are scoped to requests) the AsyncRunner class from this article is a good starting point.

Start background tasks from MVC actions using Autofac