我遇到了带有多个客户端和异步后台任务的signalR问题。
以下是我的情景: 我有多个客户端进行多次下载..他们可以同时下载文件,我使用signalR向他们发送下载进度。我处理得很好,但问题是当一个用户调用断开连接方法或他离开或刷新其页面时,signalR将断开其所有客户端不仅断开连接的那个将中断其他客户端的进度报告。我将如何解决这个问题。有没有其他办法处理它?</ p>
附加:
private async Task WriteRecords([DataSourceRequest] DataSourceRequest dataRequest,int countno, VMEXPORT[] arrVmExport, bool createHeaderyn, string filePath )
{
string fileName = filePath.Replace(System.Web.HttpContext.Current.Server.MapPath("~/") + "Csv\\", "").Replace(".csv", "");
int datapage = (countno / 192322)+1;
for (int i = 1; i <= datapage; )
{
dataRequest.Page = i;
dataRequest.PageSize = 192322;
var write = _serviceAgent.FetchByRole("", "", CurrentUser.Linkcd, CurrentUser.Rolecd).ToDataSourceResult(dataRequest);
await Task.Run(()=>write.Data.Cast<AGENT>().WriteToCSV(new AGENT(), createHeaderyn, arrVmExport, filePath));
createHeaderyn = false;
i = i + 1;
double percentage = (i * 100) / datapage;
SendProgress(percentage, countno,fileName);
}
}
以下是我的BaseController中的设置,它调用了集线器上下文:
public void SendNotification(string fileNametx, bool createdyn)
{
var context = GlobalHost.ConnectionManager.GetHubContext<SignalRHubHelper>();
context.Clients.User(CurrentUser.Usernm + '-' + CurrentUser.GUID)
.receiveNotification("Export", CurrentUser.Usernm, "info", fileNametx, createdyn);
}
public void SendProgress(double recordCount, int totalCount,string fileName)
{
var context = GlobalHost.ConnectionManager.GetHubContext<SignalRHubHelper>();
context.Clients.User(CurrentUser.Usernm + '-' + CurrentUser.GUID).reportProgress(recordCount, totalCount,fileName);
}
这是我的控制器方法:
public async Task<ActionResult> _Export([DataSourceRequest] DataSourceRequest dataRequest, string columns,int countno, string menunm)
{
var fileNametx = AgentsPrompttx + DateTime.Now.ToString(GeneralConst.L_STRING_DATE4) + ".csv";
SendNotification(fileNametx, false);
var filePath = System.Web.HttpContext.Current.Server.MapPath("~/") + "Csv\\";
var vmexport = new JavaScriptSerializer().Deserialize<VMEXPORT[]>(columns);
dataRequest.GroupingToSorting();
dataRequest.PageSize = 0; // set to zero
await WriteRecords(dataRequest,countno, vmexport, true, filePath + fileNametx);
SendNotification(fileNametx, true);
return File(filePath + fileNametx, WebConst.L_CONTENTTYPE_APP_OCTET, fileNametx);
}
JavaSciprt:
init: function (element) {
var self = this;
self.msgno = undefined;
self.sfiHubConnection = $.connection.signalRHubHelper;
self.initSignalRClients();
$.connection.hub.logging = true;
$.connection.hub.start({ transport: "longPolling" }).done(function () {
setTimeout(function () {
self.sfiHubConnection.server.getAllStatus();
self.sfiHubConnection.server.brodcastLogIn($('#usernm').text());
}, 1000);
}).fail(function () {
alert("signal Failed")
});
},
triggerReconnect: function () {
var self = this;
$.connection.hub.stateChanged(function (change) {
if (change.newState === $.signalR.connectionState.disconnected) {
$.connection.hub.stop();
self.init();
}
});
},
deleteFile: function (controllertx, filenametx) {
$('#close_dl_link').on('click', function () {
$.get(GetAppPath() + controllertx + '/_DeleteFile/?Filenametx='+filenametx, function () {
return true;
});
});
},
initSignalRClients: function () {
var self = this;
self.sfiHubConnection = $.connection.signalRHubHelper
self.sfiHubConnection.client.setOnline = function (usernm) {
if ($('#user_kgrid').data('kendoGrid') != undefined)
$('#user_kgrid').data('kendoGrid').tbody.find('td:contains("' + usernm + '")').eq(0).parent('tr').find('td:contains("Offline")').html('<span><i class="icon-ok-sign"></i></span> Online')
};
self.sfiHubConnection.client.receiveNotification = function (controller, totx, type, fileNametx, createdyn) {
if (totx == $('#usernm').text()) {
if (!createdyn) {
self.init();
var fileId=fileNametx.replace(".csv","")
var icon = "icon-download";
var title = fileId +':'+ ' <span id="' + fileId + '"></span> <br>';
var message = "Creating file kindly wait..";
var delay = 0;
SfiNotify(icon, title, message, 'info', "", "", "", "", delay);
}
else if (createdyn && fileNametx !== "") {
console.log("download available: "+fileNametx)
var elementid = fileNametx.replace(".csv", "");
$('#' + elementid).parents(".alert").each(function () {
$(this).remove();
});
var icon = "icon-download";
var title = " File ready for download !<br>" + "<strong>" + fileNametx + "</strong><br>";
var message = "Click here to download the file!";
var url = GetAppPath() + controller + '/_Download/?filenametx=' + fileNametx;
var delay = 0;
SfiNotify(icon, title, message, 'info', url, "", "", "", delay);
if ($('#close_dl_link').length > 0) {
self.deleteFile(controller, fileNametx);
}
}
}
else
return false;
};
self.sfiHubConnection.client.reportProgress = function (recordCount, totalRecord, fileName) {
var progress = recordCount + "% of " + totalRecord;
console.log("PROGRESS FOR: " + fileName + "TOTAL: "+recordCount);
if ($('#' + fileName).length > 0) {
if (recordCount > 100)
return false;
$('#' + fileName).text(progress);
}
else if($('#' + fileName).length == 0)
{
if (recordCount > 100)
return false;
var icon = "icon-download";
var title = ' Processing Records <span id=' + fileName + '>' + progress + '</span> <br>';
var message = "Creating file kindly wait..";
var delay = 0;
SfiNotify(icon, title, message, 'info', "", "", "", "", delay);
}
};