我想通过线程发送通知。我创建了一个迭代自我无限时间的线程。这是我的代码。
public static class ThreadStartUp
{
public static void GetThread()
{
var thread = new Thread(ReminderHelperClas.IterateMethod);
thread.Start();
}
}
MY Static class with methods is
public static class ReminderHelperClas
{
public static void CheckReminder()
{
try
{
const string usernamesendby = "38";
const string message = "Please give feedback to assigned task.";
var chathub = new ChatHub();
using (var db = new DatabaseContext())
{
var datetimenow = DateTime.Now;
const TaskAssignStatus recordstatus = (TaskAssignStatus)3;
var remindermodel =
db.ActionTaskVarainceCategories.Where(x => x.TaskAssignStatus != recordstatus)
.Select(x => x)
.ToList();
foreach (var item in remindermodel)
{
if (item.ToDate == datetimenow || item.ToDate < datetimenow)
{
var username = db.Users.Where(u => u.ID == item.AssignedToID).Select(u => u.UserName).FirstOrDefault();
var msgclass = new TaskMessagingModel { FromId = 38, Message = message, UserName = username, ToId = item.AssignedToID };
SaveMessages.TaskSaveMessage(msgclass);
chathub.Send(usernamesendby, message, username);
}
}
}
}
catch (Exception ex)
{
throw ex;
}
}
public static void IterateMethod()
{
try
{
while (true)
{
CheckReminder();
Thread.Sleep(10000);
}
}
catch (Exception ex)
{
throw ex;
}
}
}
当保存消息时,我调用了发送通知方法,但它给了我null异常,虽然我提供了所有参数。请帮我这个。
答案 0 :(得分:0)
您无法初始化集线器类并调用其方法。要使集线器调用方法,您应该使用 GlobalHost.ConnectionManager.GetHubContext()传入要获取其对象的集线器类。例如
private readonly IHubContext _chatHub = GlobalHost.ConnectionManager.GetHubContext<ChatHub>();
然后,您现在可以使用聊天中心上下文并调用要发送提醒的组或 Clients 属性中的方法,以便
_chatHub.Clients.Client(clientConnectionString)
.Send(usernamesendby, message, username);
有关详情,建议您查看本教程http://www.asp.net/signalr/overview/getting-started/tutorial-server-broadcast-with-signalr
修改强> clientConnectionString 是您要将消息发送到的特定客户端的 connectionId 。所以问题是你是否将消息发送给特定的客户?如果是特定客户端,则必须覆盖 ChatHub 中的 OnConnected()方法,并在内存中获取并保留connectionId或在数据库中,然后在CheckReminder方法中,您现在将访问connectionId并使用它将消息发送给特定用户。你可以这样做。
public override Task OnConnected()
{
string connectionId = Context.ConnectionId;
IPrincipal user = Context.User;
//Save connection.
_clientManager.AddToCorrectGroup(user, connectionId;
return base.OnConnected();
}