在ASP.NET中使用后台工作与AJAX [英] Using a background worker in ASP.NET with AJAX

查看:89
本文介绍了在ASP.NET中使用后台工作与AJAX的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要执行一个后台任务,有一个进度条,显示比例进行,取消按钮。任务细节不谈,现在,我只想得到一个例子工作,所以我只是有三个主要的事件处理程序(DoWork的,ProgressChanged和RunWorkerCompleted),而只是增加一个计数器,睡在DoWork的50ms的一环。然而,它不只是一次在结束更新

I have the need to perform a background task that has a progress bar that shows percentage done and a cancel button. Task specifics aside, for now, I just want to get an example working, so I just have the three main event handlers (DoWork, ProgressChanged, and RunWorkerCompleted) and a loop that just increments a counter and sleeps for 50ms in DoWork. However, it doesn't update except for once at the end.

在Windows窗体我使用一个后台工作,并正确运行没有任何问题。我想只要使用同样的code。不过,我已经看到的东西,说ASP.NET必须使用AJAX来获得相同的功能。所以,我的问题是:

In Windows Forms I use a Background worker and it functions correctly without any issues. I'd like to just use this same code. However, I have been seeing stuff that says ASP.NET must use AJAX to get the same functionality. So my questions are:

1)我真的需要AJAX使用后台工作?

1) Do I really need AJAX to use the background worker?

2)如果是,我确实需要AJAX,什么是最简单,最简单的方法一个人,不知道AJAX缝补的事情可以做,以获得后台工作启动和运行在一个ASP.NET网页?

2) If yes, I do need AJAX, what is the easiest, most simplest way a person that doesn't know a darn thing about AJAX could do to get the Background worker up and running on an ASP.NET webpage?

3)如果没有,我不需要AJAX,任何人都可以点我不使用它工作示例?我很感兴趣,即使它使用比后台人员的一些其它线程的方法。

3) If no, I don't need AJAX, can anyone point me to a working sample that doesn't use it? I am interested even if it uses some other threading method than background workers.

对不起,多部分的问题!如果你能回答一个或另一个,这将是更AP preciated。我真的不介意我最终哪种方法使用起来,只要它的作品。

Sorry for the multi-part question! If you can answer one or the other, it would be much appreciated. I don't really mind which method I end up using as long as it works.

code从的.cs页面引用:

Code for reference from the .cs page:

 protected void bwProcess_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
 { 
     lblProgress.Text = "Task Complete: " + e.Result;
 }

 protected void bwProcess_ProgressChanged(object sender, ProgressChangedEventArgs e)
 {
     lblProgress.Text = e.ProgressPercentage.ToString();
 }

 protected void bwProcess_DoWork(object sender, DoWorkEventArgs e)
 {
     for (int i = 0; i <= 100; i++)
     {
         if (bwProcess.CancellationPending)
         {
             lblProgress.Text = "Task Cancelled.";
             e.Cancel = true;
             return;
         }
         bwProcess.ReportProgress(i);
         Thread.Sleep(50);
     }
     e.Result = "100%";
}

protected void BWClick(object sender, EventArgs e)
{
    lblProgress.Text = "Firing Process...";
    bwProcess = new BackgroundWorker();
    bwProcess.WorkerReportsProgress = true;
    bwProcess.WorkerSupportsCancellation = true;
    bwProcess.DoWork += new DoWorkEventHandler(bwProcess_DoWork);
    bwProcess.ProgressChanged += new ProgressChangedEventHandler(bwProcess_ProgressChanged);
    bwProcess.RunWorkerCompleted += new RunWorkerCompletedEventHandler(bwProcess_RunWorkerCompleted);

    if (bwProcess != null)
    {
        bwProcess.RunWorkerAsync("StartAsynchronousProcess");
    }
}

其他说明:我已经进入异步=true和的EnableSessionState =只读到@Page

Other notes: I have entered Async="True" and EnableSessionState="ReadOnly" into the @Page.

在此先感谢!

推荐答案

Web编程提供的这是很容易想当然,当桌面编程许多挑战。从一个移动到另一个可能需要很多的变化。产卵长期运行的线程是那些东西,需要更多的照顾,以避免陷阱之一。应用程序池不知道你产卵,所以当它回收它会杀死那些线程导致应用程序意外行为线程。更多的关于<一看到这个帖子href="http://stackoverflow.com/questions/536681/can-i-use-threads-to-carry-out-long-running-jobs-on-iis">Can我使用的线程进行长时间运行的工作在IIS上?

Web programming offer's many challenges which are easy to take for granted when desktop programming. Moving from one to the other can require a lot of changes. Spawning long-running threads is one of those things that require more care to avoid pitfalls. The application pool does not know about threads that you spawn so when it recycles it will kill those threads causing unexpected behavior in your application. See this post for more about that, Can I use threads to carry out long-running jobs on IIS?

这意味着你需要使用一个更持久的手段来跟踪进度。数据库将可能是最好的,但即使是文件将持久化池被回收之后。

This means you need to use a more persistent means to keep track of progress. A database would probably be best, but even a file would persist after the pool is recycled.

AJAX将是完美的,因为这可以让你从数据库异步地拉进步的背景和更新网页。下面是你会如何实现这一breif例子。所有的百分比计算都在服务器端完成。

AJAX would be perfect for this because it will allow you to pull the progress from the database asynchronously in the background and update the webpage. Here is a breif example of how you might achieve this. All the percentage calculations are done on server side.

function getProgress() {
    $.ajax({
        url: '/progress',           // send HTTP-GET to /progress page
        dataType: 'json',           // return format will be JSON
        success: function(result) { // function to run once the result is pulled
            $("#p1").html('Percentage: %' + result);
            if (result == "100")
                clearInterval(window.progressID);
        }
    });
}

function startGetProgress() {
    window.progressID = setInterval(getProgress, 10000); // update progress every 10 seconds
}

上面的例子使用JQuery的AJAX方法, http://api.jquery.com/jQuery.ajax / 所以你需要引用jQuery库。

The above example uses JQuery ajax method, http://api.jquery.com/jQuery.ajax/ so you will need to reference the JQuery library.

无论你是用web表单或MVC,你可以添加Web API控制器来处理Ajax请求。让我知道如果你需要我澄清什么。

Whether you are using webforms or mvc you can add a web api controller to handle the ajax request. Let me know if you need me to clarify anything.

这篇关于在ASP.NET中使用后台工作与AJAX的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆