I am executing a long-running process using Hangfire. I want to let the
client know the progress (% complete) using Microsoft.AspNet.SignalR.
So far I am able to execute the job, but I cannot understand how to add
the SignalR part. This is what I have so far.
// BEGIN Startup.cs
public partial class Startup {
public void Configuration(IAppBuilder app) {
ConfigureAuth(app);
app.MapSignalR();
GlobalConfiguration.Configuration.UseSqlServerStorage(
"DefaultConnection",
new SqlServerStorageOptions { QueuePollInterval = TimeSpan.FromSeconds(1) });
app.UseHangfireDashboard();
app.UseHangfireServer();
}
}
// END Startup.cs
// BEGIN TestForm.cs
public partial class TestForm : System.Web.UI.Page
{
protected void cmdOK_Click(object sender, EventArgs e)
{
string id =
BackgroundJob.Enqueue(() => LongRunner.LongRunningMethod());
}
}
// END TestForm.cs
// BEGIN LongRunner.cs
class LongRunner
{
static int _percent = 0;
// declare public method to be executed by Hangfire
public static void LongRunningMethod()
{
int oldPercent = _percent;
for (int i = 0; i < 600; i++)
{
// if % complete changes, notify client
_percent = i / 6;
if (oldPercent != _percent)
{
oldPercent = _percent;
// I believe that this is where SignalR comes in
}
System.Threading.Thread.Sleep(100);
}
}
}
// END LongRunner.cs
This works. When I go to the dashboard, I see that the job executed and
it took about 1 minute as expected.
I want to update the TestForm web page when there is something to
report, i.e., when the percentage complete increases. I understand that
I have to define a hub:
// BEGIN LongRunnerHub.cs
class LongRunnerHub : Hub
{
// Don't really know what this does
await Groups.Add(Context.ConnectionId, "LongRunnerGroup");
// or what should be here.
}
// END LongRunnerHub.cs
I must also change my long running method:
// BEGIN LongRunner.cs
class LongRunner
{
static int _percent = 0;
// declare public method to be executed by Hangfire
public static void LongRunningMethod()
{
var hubContext = GlobalHost.ConnectionManager
.GetHubContext<LongRunnerHub>();
hubContext.Clients.Group("LongRunnerGroup")
. // Don't know what goes here
int oldPercent = _percent;
for (int i = 0; i < 600; i++)
{
// if % complete changes, notify client
_percent = i / 6;
if (oldPercent != _percent)
{
oldPercent = _percent;
// Notify client, but how?
}
System.Threading.Thread.Sleep(100);
}
}
}
// END LongRunner.cs
Please help me fill in the blanks. All the SignalR examples show HTML pages + Javascript. Is it that I must write Javascript or will ASP.NET WebForms take care of that for me?