Nic*_*dke 5 c# asp.net asp.net-mvc asynchronous signalr
以下服务器端代码用于启动一个长时间运行的任务,该任务将通过 SignalR 将更新发布到 Web 前端。我在前端放置了一个按钮,然后我想根据用户的请求停止任务。
当前端触发器的Stop方法时,tokenSource为空。我怀疑,这是因为它没有到达ChartHub产生任务的同一个实例。
using System;
...
using System.Security.Principal;
namespace dvvWeb.Hubs
{
public class ChartHub : Hub
{
CancellationTokenSource tokenSource;
CancellationToken ct;
public void Start(string serverName, string dbName, string numberOfPoints, string pollingFrequency)
{
ConfigModel config = new ConfigModel();
tokenSource = new CancellationTokenSource();
ct = tokenSource.Token;
config.Servername = HttpUtility.UrlDecode(serverName);
config.DbName = HttpUtility.UrlDecode(dbName);
config.Preferences.NumberOfPoints = int.Parse(numberOfPoints);
config.Preferences.PollingFrequency = int.Parse(pollingFrequency);
dvvGraphingModel graphingModel = new dvvGraphingModel();
dvvGraphingHelper graphingHelper = new dvvGraphingHelper(graphingModel, config.Servername, config.DbName);
graphingModel = graphingHelper.Tick(config.Preferences);
var identity = WindowsIdentity.GetCurrent();
Task.Run(() => workItemAsync(ct, graphingModel, graphingHelper, config, identity));
}
public void Stop()
{
tokenSource.Cancel();
}
private async Task<CancellationToken> workItemAsync(CancellationToken ct, dvvGraphingModel graphingModel, dvvGraphingHelper graphingHelper, ConfigModel configModel, WindowsIdentity identity)
{
await addDataAsync(ct, graphingModel, graphingHelper, configModel, identity);
return ct;
}
private async Task<CancellationToken> addDataAsync(CancellationToken ct, dvvGraphingModel graphingModel, dvvGraphingHelper graphingHelper, ConfigModel configModel, WindowsIdentity identity)
{
try
{
while(!ct.IsCancellationRequested)
{
identity.Impersonate();
Clients.Caller.addPointToChart(JsonConvert.SerializeObject(graphingModel));
System.Threading.Thread.Sleep(configModel.Preferences.PollingFrequency * 1000);
graphingModel = graphingHelper.Tick(configModel.Preferences);
}
}
catch (TaskCanceledException tce)
{
Trace.TraceError("Caught TaskCanceledException - signaled cancellation " + tce.Message);
}
return ct;
}
}
}
Run Code Online (Sandbox Code Playgroud)
我会创建一个ConcurrentDictionary<string, CancellationTokenSource>“字符串”,其中“字符串”可能是用户名/ID,或者可能是
ConcurrentDictionary<IUserIdentity, CancellationTokenSource>。
好吧,在用户一次只能启动一个进程的情况下\xc2\xb4s。
\n\n该字典将位于 Hub 之外的 Singleton 类中。您的集线器只是调用单例中方法的代理。
\n\nYourSingleton.Instance.Start(userId, serverName, dbName, numberOfPoints, pollingFrequency);\nRun Code Online (Sandbox Code Playgroud)\n\n和
\n\nYourSingleton.Instance.Stop(userId);\nRun Code Online (Sandbox Code Playgroud)\n\n然后,你可以这样做:
\n\npublic void Stop(string userId)\n{\n CancellationTokenSource tokenSource;\n if(dictionary.TryGetValue(userId, out tokenSource))\n {\n tokenSource.Cancel();\n dictionary.TryRemove(userId out tokenSource);\n }\n}\nRun Code Online (Sandbox Code Playgroud)\n
| 归档时间: |
|
| 查看次数: |
1427 次 |
| 最近记录: |