Signalr backend controller setup:
namespace Antz.App.SignalR.Hubs
{
public class ProgressHub : Hub
{
public static bool IsCancelled = false;
public void SendProgress(string progressMessage, int progressCount, int totalItems)
{
//Thread.Sleep(1);
var hubContext = GlobalHost.ConnectionManager.GetHubContext<ProgressHub>();
var percentage = (progressCount * 100) / totalItems;
hubContext.Clients.All.AddProgress(progressMessage, percentage + "%");
}
public void IsCancelledUpload()
{
IsCancelled = true;
}
}
}
Javscript:
signalrConnection = $.hubConnection("/SignalR", { useDefaultPath: false });
signalrProxy = signalrConnection.createHubProxy('ProgressHub');
signalrProxy.on('AddProgress', function (message, percentage) {
UpdateProgressBar(percentage);
});
/* signalrConnection.logging = true;*/
signalrConnection.start({ transport: 'longPolling' }).then(function () {
console.log("Connection Started");
});
signalrConnection.disconnected(function () {
console.log('Disconnected');
setTimeout(function () {
signalrConnection.start({ transport: 'longPolling' }).then(function () {
console.log("Connection Started");
});
}, 3000);
});
signalrConnection.error(function (error) {
console.log(error);
});
function UpdateProgressBar(percentage) {
const progressBar = document.querySelector(".progress-bar");
progressBar.style.opacity = "1";
progressBar.style.width = percentage;
progressBar.innerHTML = percentage;
if (percentage === "100%") {
progressBar.style.width = "";
progressBar.innerHTML = "";
}
}
Upload function backend controller:
ProgressHub progressHub = new ProgressHub();
var refNoList = new List<string>();
await Task.Run(async () =>
{
foreach (ArrayList row in data3)
{
recordProcessed++;
rowIndex++;
// skip row 1 as it's a header
if (rowIndex == 1)
{
continue;
}
progressHub.SendProgress("Process in progress...", rowIndex, totalRows);
//await Task.Delay(5000); // Introduce a small delay
bool all_pass = true;
string docType = row[0].ToString().Trim();
string refNo = row[1].ToString().Trim();
string vendor = row[2].ToString().Trim();
string remark = row[3].ToString().Trim();
I’ve tried to put a static field on the class ProgressHub
and if the user was clicked the cancel button, the button will trigger the signalr to invoke the function IsCancelledUpload
which is use to update the IsCancelled
boolean to true. So Excel upload function will check if the boolean is true, the loop will be break. But using static is not a wise choice, so I’m seeking another approach for this.