我将此代码基于此示例http://weblogs.asp.net/seanmcalinden/archive/2009/11/15/asynchronous-processing-in-asp-net-mvc-with-ajax-progress-bar.aspx 使用MVC3、C#、jQuery、Ajax ++
我的html
<div>
<a href="#" id="startProcess">Start Long Running Process</a>
</div>
<br />
<div id="statusBorder">
<div id="statusFill">
</div>
</div>
html的javascript部分
var uniqueId = '<%= Guid.NewGuid().ToString() %>';
$(document).ready(function (event) {
$('#startProcess').click(function () {
$.post("SendToDB/StartLongRunningProcess", { id: uniqueId,
//other parameters to be inserted like textbox
}, function () {
$('#statusBorder').show();
getStatus();
});
event.preventDefault;
});
});
function getStatus() {
var url = 'SendToDB/GetCurrentProgress/' + uniqueId;
$.get(url, function (data) {
if (data != "100") {
$('#status').html(data);
$('#statusFill').width(data);
window.setTimeout("getStatus()", 100);
}
else {
$('#status').html("Done");
$('#statusBorder').hide();
alert("The Long process has finished");
};
});
}
一个完整的班级来帮助
public class ProgressBarManager
{
private static object syncRoot = new object();
/// <summary>
/// Gets or sets the process status.
/// </summary>
/// <value>The process status.</value>
private static IDictionary<string, int> ProcessStatus { get; set; }
/// <summary>
/// Initializes a new instance of the <see cref="MyLongRunningClass"/> class.
/// </summary>
public ProgressBarManager()
{
if (ProcessStatus == null)
{
ProcessStatus = new Dictionary<string, int>();
}
}
/// <summary>
/// Processes the long running action.
/// This is how it was in sample code. Not used anymore.
/// </summary>
/// <param name="id">The id.</param>
//public string ProcessLongRunningAction(string id)
//{
// for (int i = 1; i <= 100; i++)
// {
// Thread.Sleep(100);
// lock (syncRoot)
// {
// ProcessStatus[id] = i;
// }
// }
// return id;
//}
public void SetStatus(string id, int value)
{
lock (syncRoot)
{
ProcessStatus[id] = value;
}
}
/// <summary>
/// Adds the specified id.
/// </summary>
/// <param name="id">The id.</param>
public void Add(string id)
{
lock (syncRoot)
{
ProcessStatus.Add(id, 0);
}
}
/// <summary>
/// Removes the specified id.
/// </summary>
/// <param name="id">The id.</param>
public void Remove(string id)
{
lock (syncRoot)
{
ProcessStatus.Remove(id);
}
}
/// <summary>
/// Gets the status.
/// </summary>
/// <param name="id">The id.</param>
public int GetStatus(string id)
{
lock (syncRoot)
{
if (ProcessStatus.Keys.Count(x => x == id) == 1)
{
return ProcessStatus[id];
}
else
{
return 100;
}
}
}
}
这是控制器,这就是我可能做错了什么的地方。
delegate string ProcessTask(string id);
ProgressBarManager longRunningClass = new ProgressBarManager();
//Some global variables. I know it is not "good practice" but it works.
private static int _GlobalSentProgress = 0;
private static int _GlobalUsersSelected = 0;
/// <summary>
/// Starts the long running process.
/// </summary>
/// <param name="id">The id.</param>
public void StartLongRunningProcess(string id,
//other parameters
)
{
longRunningClass.Add(id);
int percentDone = 0;
var batchId = Guid.NewGuid().ToString("N");
var costd = cost.ToDecimal();
int sent = 0;
IEnumerable<BatchListModel> users;
users = new UserService(_userRepository.Session).GetUsers(
//several parameters)
foreach (var c in users)
{
try
{
var usr = _userRepository.LoadByID(c.ID);
var message = new DbLog
{
//insert parameters
};
_DbLogRepository.Save(message);
sent++;
//MyLog.WriteLine("Sent = " + sent); This is 1 more each time it loops
//MyLog.WriteLine("GlobalUsersSelected = " + _GlobalUsersSelected); This one is set in another function not shown.
double _GlobalSentProgress = (double)sent / (double)_GlobalUsersSelected * 100;
//MyLog.WriteLine("SentProgress = " + _GlobalSentProgress);
if (percentDone < 100)
{
//percentDone = doSomeWork();
percentDone = Convert.ToInt32(_GlobalSentProgress);
//MyLog.WriteLine("percentDone = " + percentDone); This one shows same as GlobalSentProgress except the decimals are removed
longRunningClass.SetStatus(id, percentDone);
}
}
catch (Exception e)
{
MyLog.WriteLine("ERR:" + e);
}
}
longRunningClass.Remove(id);
//Under here is how it was done in the example tutorial.
//I think these should be implemented somehow.
//This may be the root of my problem
//ProcessTask processTask = new ProcessTask(longRunningClass.ProcessLongRunningAction);
//processTask.BeginInvoke(id, new AsyncCallback(EndLongRunningProcess), processTask);
}
/// <summary>
/// Ends the long running process.
/// </summary>
/// <param name="result">The result.</param>
public void EndLongRunningProcess(IAsyncResult result)
{
ProcessTask processTask = (ProcessTask)result.AsyncState;
string id = processTask.EndInvoke(result);
longRunningClass.Remove(id);
}
/// <summary>
/// Gets the current progress.
/// </summary>
/// <param name="id">The id.</param>
public ContentResult GetCurrentProgress(string id)
{
this.ControllerContext.HttpContext.Response.AddHeader("cache-control", "no-cache");
var currentProgress = longRunningClass.GetStatus(id).ToString();
return Content(currentProgress);
}
有谁知道有什么问题?非常感谢任何帮助。我已经被困了好几天了。
在插入 100% 完成之前,不会输入一些应该更新“进度”的断点。现在,带有进度条的 div 永远不会出现。
编辑:在进行插入的循环中,我确实有这个计算:
double _GlobalSentProgress = (double)sent / (double)_GlobalUsersSelected * 100;
然后我将 _GlobalSentProgress 转换为正常的 int
percentDone = Convert.ToInt32(_GlobalSentProgress);
所以它不再有任何小数。
如果我能在每次循环时将这个“percentDone”变量(它完美地显示了我在插入中的百分比)异步发送到javascript中的“数据”变量中,它就会起作用。然后“数据”会一直执行“状态填充”并正确显示条形图。
function getStatus() {
var url = 'SendToDB/GetCurrentProgress/' + uniqueId;
$.get(url, function (data) {
if (data != "100") {
$('#status').html(data);
$('#statusFill').width(data);
window.setTimeout("getStatus()", 100);
}
else {
$('#status').html("Done");
$('#statusBorder').hide();
alert("The Long process has finished");
};
});
但老实说,这是我第一次处理异步变量,所以我对如何做这些事情非常迷茫。