简体   繁体   English

Signalr-闲置一段时间后运行任务

[英]Signalr - Run task after period of inactivity

I want to call a function after a period of inactivity (regardless of whether the client is connected or not) to clean up / dispose of data. 我想在一段时间不活动(无论是否连接客户端)后调用一个函数,以清理/处置数据。 Basically, I am creating a new instance of a class for each client that is connected and storing it in a Dictionary, but I don't want to keep that instance there if the client is inactive / disconnected for a period of time (eg 30 minutes) to free up memory. 基本上,我为每个已连接的客户端创建一个新的类实例,并将其存储在Dictionary中,但是如果该客户端在一段时间内处于非活动状态/断开连接,则我不希望将该实例保留在那里。分钟)以释放内存。 Is this possible with Signalr? Signalr有可能吗?

You can use the OnDisconnected event in your Hub to know when your client is not active , and clear up your memory. 您可以使用集线器中的OnDisconnected事件来了解客户端何时处于非活动状态,并清除内存。

public override Task OnDisconnected() { // Free Your memory here return base.OnDisconnected(); 公共重写Task OnDisconnected(){//释放您的内存在这里返回base.OnDisconnected(); } }

and you can configure the disconnect event time period 您可以配置断开连接事件的时间段

Found my answer here . 在这里找到我的答案。 Basically, you can create a variable like so: 基本上,您可以像这样创建一个变量:

static public Dictionary<string, DateTime> LastConnectionTime = new Dictionary<string, DateTime>();

Whenever the user accesses a function, you can update the last time like so: 每当用户访问功能时,您都可以像这样上次更新:

LastConnectionTime[Context.User.Identity.Name] = DateTime.Now;

Then, in your Globals.asax: 然后,在您的Globals.asax中:

    protected void Application_Start()
    {
        // ...

        AddTask("HubInactivity", 120);
    }

    private void AddTask(string name, int seconds)
    {
        OnCacheRemove = new CacheItemRemovedCallback(CacheItemRemoved);
        HttpRuntime.Cache.Insert(name, seconds, null,
            DateTime.Now.AddSeconds(seconds), Cache.NoSlidingExpiration,
            CacheItemPriority.NotRemovable, OnCacheRemove);
    }

    public void CacheItemRemoved(string k, object v, CacheItemRemovedReason r)
    {
        if (k == "HubInactivity")
        {
            var time = DateTime.Now;

            // HubHelpers is where I kept the dictionary in my case
            foreach (var identity in Hubs.HubHelpers.LastConnectionTime.Keys)
            {
                var lastConnection = Hubs.HubHelpers.LastConnectionTime[identity];

                if ((time - lastConnection).TotalMinutes > 30.0)
                {
                    // Do stuff.
                }
            }
        }

        // re-add our task so it recurs
        AddTask(k, Convert.ToInt32(v));
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM