这是一个非常简单的方法:
您是否考虑过使用静态列表?
列表中的每个项目都是运行后台进程的处理程序的实例。您需要识别每个处理程序,最简单的方法是Guid
为每个处理程序使用一个。
这是一个示例工作代码:
输出
如您所见,每个窗口都会触发一个新进程,并且每个窗口都会独立更新
ASPX
<head runat="server">
<title></title>
<script type="text/javascript" src="Scripts/jquery-1.7.2.min.js"></script>
<script type="text/javascript" src="Scripts/jquery.timer.js"></script>
<script type="text/javascript">
var timer;
var currentProcess;
function getProgress() {
$.ajax({
url: 'LongTimeOperations.aspx/GetStatus',
data: '{"processID": "' + currentProcess + '"}',
contentType: 'application/json; charset=utf-8;',
dataType: 'json',
type: "POST",
async: true,
cache: false,
success: function (msg) {
$("#res").append("<br/>" + msg.d);
var r = msg.d;
if (typeof (r) === 'undefined' || r === null) {
timer.stop();
}
},
error: function (hxr) {
alert(hxr.responseText);
}
});
}
$(function () {
$("#start").click(function () {
$.ajax({
url: 'LongTimeOperations.aspx/StartProcess',
data: '{}',
contentType: 'application/json; charset=utf-8;',
dataType: 'json',
type: "POST",
async: true,
cache: false,
success: function (msg) {
alert(msg.d);
currentProcess = msg.d;
timer = $.timer(getProgress, 2000, true);
},
error: function (hxr) {
alert(hxr.responseText);
}
});
});
});
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<input type="button" id="start" value="Start Process" />
<p>
<div id="res"></div>
</p>
</div>
</form>
</body>
背后的代码
public static List<CurrentProcess> Processes = new List<CurrentProcess>();
[WebMethod]
public static Guid StartProcess()
{
Mutex mutex = new Mutex();
mutex.WaitOne();
var star = Thread.CurrentThread.ManagedThreadId.ToString();
var p = new CurrentProcess(Guid.NewGuid());
Processes.Add(p);
var o = Observable.Start(() =>
{
var cap = p;
for (int i = 0; i < 10; i++)
{
Thread.Sleep(2000);
var cp = Processes.FirstOrDefault(x => x.ID == cap.ID);
if (cp != null)
cp.Status = string.Format("Current Process ID: {0}, Iteration: {1}, Starting thread: {2}, Execution thread: {3}",
cp.ID.ToString(),
i.ToString(),
star,
Thread.CurrentThread.ManagedThreadId.ToString()
);
}
Processes.RemoveAll(x => x.ID == cap.ID);
}, Scheduler.NewThread);
mutex.ReleaseMutex();
mutex.Close();
return p.ID;
}
[WebMethod]
public static string GetStatus(Guid processID)
{
var p = Processes.FirstOrDefault(x => x.ID == processID);
if (p != null)
return p.Status;
return null;
}
}
public class CurrentProcess
{
public Guid ID { get; set; }
public string Status { get; set; }
public CurrentProcess (Guid id)
{
this.ID = id;
}
}
使用的库
在这个示例中,我使用 Rx 创建一个新线程,您可以将其更改为使用另一种方法