数据库更改时的 LifeUpdate 抛出错误

LifeUpdate on Database change Throws error

我遵循了这个 guide,并且我确实设法让它达到 post 我的数据库的值,但是当我更改数据库中的内容时它不会更新页面。

所以当我调试 NotificationHub.cs 这两行时抛出一个错误。

IHubContext context = GlobalHost.ConnectionManager.GetHubContext<NotificationHub>();
return context.Clients.All.RecieveNotification(totalNewMessages, totalNewCircles, totalNewJobs, totalNewNotification);

它抛出的错误是:

An exception of type 'Microsoft.CSharp.RuntimeBinder.RuntimeBinderException' Occurred in System.Core.dll but was not handled in user code

Additional information: The type 'System.Threading.Tasks.Task ' can not be implicitly converted to 'string'

发送通知代码如下:

public string SendNotifications()
{
    using (var connection = new SqlConnection(ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString))
    {
        string query = "SELECT NotificationNumber FROM [dbo].[NotificationStatus] WHERE UserID=" + "1";
        connection.Open();
        using (SqlCommand command = new SqlCommand(query, connection))
        {
            try { 
            command.Notification = null;
            DataTable dt = new DataTable();
            SqlDependency dependency = new SqlDependency(command);
            dependency.OnChange += new OnChangeEventHandler(dependency_OnChange);                
            if (connection.State == ConnectionState.Closed)
                connection.Open();
            var reader = command.ExecuteReader();
            dt.Load(reader);
            if (dt.Rows.Count > 0)
            {
                totalNewMessages = Int16.Parse(dt.Rows[0]["NotificationNumber"].ToString());
            }
            connection.Close();
        }
        catch(Exception ex)
        {
            throw;
        }
        }
    }
    IHubContext context = GlobalHost.ConnectionManager.GetHubContext<NotificationHub>();
    return context.Clients.All.RecieveNotification(totalNewMessages);
}

希望有人能指出哪里不对。

context.Clients.All.RecieveNotification(totalNewMessages)是一个动态方法,它的return类型是Task;这不能转换为字符串,这就是您要从 SendNotifications return 尝试得到的字符串。所以你需要更改签名,例如:

public Task SendNotifications();