可以看到只有1个实例的长期运行任务

时间:2019-06-01 17:55:01

标签: c# asp.net

一般问题。向用户提供网页,该会话的数据输入输出。在c#和asp.net中,如何在服务器上创建一个页面,该页面持续执行任务并且仅运行1个实例。它一遍又一遍地做某事。然后,根据需要,一个人可以查看其操作。

1 个答案:

答案 0 :(得分:0)

您可以在单独的线程中运行长任务,并在需要时与其通信。像这样的东西。

protected void btnRun_Click(object sender, EventArgs e)
{
    var jobState = new StateInfo()
    {
        Id = 1,
        Counter = 0,
        Content = "Start the job",
        Cancelled = false,
        Completed = false
    };
    Session["job"] = jobState;
    System.Threading.ThreadPool.QueueUserWorkItem(
        new System.Threading.WaitCallback(LongJob),
        jobState
        );//returns immediately
    lblToken.Text += "<br />" + jobState.Counter.ToString() 
        + " Completed: " + jobState.Completed.ToString()
        + " Cancelled: " + jobState.Cancelled.ToString()
        + "<br />" + jobState.Content;
    btnCancel.Visible = true;
    btnCheck.Visible = true;
}

protected void btnCancel_Click(object sender, EventArgs e)
{
    var jobState = Session["job"] as StateInfo;
    if (!jobState.Completed)
        jobState.Cancelled = true;
    System.Threading.Thread.Sleep(1000);//wait for the next loop to complete
    lblToken.Text += "<br />" + jobState.Counter.ToString()
        + " Completed: " + jobState.Completed.ToString()
        + " Cancelled: " + jobState.Cancelled.ToString()
        + (jobState.Completed || jobState.Cancelled ? "<br />" + jobState.Content : "");
}

protected void btnCheck_Click(object sender, EventArgs e)
{
    var jobState = Session["job"] as StateInfo;
    lblToken.Text += "<br />" + jobState.Counter.ToString()
        + " Completed: " + jobState.Completed.ToString()
        + " Cancelled: " + jobState.Cancelled.ToString()
        + (jobState.Completed || jobState.Cancelled ? "<br />" + jobState.Content : "");
}

private void LongJob(object state)
{
    var jobState = state as StateInfo;
    do
    {
        System.Threading.Thread.Sleep(1000);
        jobState.Counter++;
        if (jobState.Counter >= 100)
        {
            jobState.Completed = true;
            jobState.Content = "The job is completed";
        }
        else if (jobState.Cancelled)
            jobState.Content = "The job is cancelled";
    }
    while (!jobState.Cancelled && !jobState.Completed);
}
[Serializable]
class StateInfo
{
    public int Id { get; set; }
    public int Counter { get; set; }
    public string Content { get; set; }
    public bool Cancelled { get; set; }
    public bool Completed { get; set; }
}

和明显的客户端控制。

<asp:Label ID="lblToken" runat="server"></asp:Label><br />
<asp:Button runat="server" ID="btnRun" OnClick="btnRun_Click" Text="Run" />
<asp:Button runat="server" ID="btnCheck" OnClick="btnCheck_Click" Text="Check State" Visible="false" />
<asp:Button runat="server" ID="btnCancel" OnClick="btnCancel_Click" Text="Cancel" Visible="true" />