如何停止在ASP.net 2.0中的新线程中运行的Timer [英] How to stop Timer that run in new thread in ASP.net 2.0

查看:84
本文介绍了如何停止在ASP.net 2.0中的新线程中运行的Timer的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家好,

我想知道用户是在线还是离线,
并且我使用计时器每5秒更新一次用户在数据库中的最后一次访问,

我在ASP.net 2.0中使用System.Timers.Timer

当我使用它时,我注意到elapse事件在新线程中运行,因为它不会引发回发事件,但是问题是,当我关闭浏览器时,elapse事件仍在引发并且没有停止. >
我想在关闭浏览器或导航到另一个网站时停止计时器,是否有任何方法可以停止计时器?

同样,当我退出并执行语句_timer.Stop()时,计时器也不会停止.

那就是所有代码:

Hi everyone,

I want to know if User is online or offline,
and i used timer to update User last visit in database every 5 seconds,

I am using System.Timers.Timer in ASP.net 2.0,

When I use it I notice that the elapse event is run in new thread as it does not cause a Postback event to fire, but the problem is that when I close the browser the elapse event is still being raised and not stopped.

I want to stop the timer when the browser is closed or when I navigate to another website, is there any approach to stop it?

also when i make Sign out and execute statement _timer.Stop() the Timer not stopped.

That is all code:

public partial class MainMasterPage : System.Web.UI.MasterPage
{
    protected System.Timers.Timer _timer;

    protected void Page_Init(object sender, EventArgs e)
    {
        _timer = new System.Timers.Timer(5000);

        _timer.Elapsed += new System.Timers.ElapsedEventHandler(timer_Elapsed);
    }

    protected void Page_Load(object sender, EventArgs e)
    {
        if (Request.IsAuthenticated)
        {
            _timer.Start();
        }
        else
        {
            _timer.Stop();
        }
    }

    private void timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
    {
        // Code here for update User last visit in database
    }
}

推荐答案

鉴于您想知道用户是否仍在您的网站上,您可以创建一个1px的空白图片,该图片位于您的页面上,使用ajax每n秒刷新一次链接.如果将客户端的会话ID附加到图像URL,则可以在服务器上检测到用户仍处于连接状态.
Given that you want to know if a user is still on your site you could create a 1px blank image that sits somewhere on your page and use ajax to refresh the link every n seconds. If you append the session id of the client to the image url you can detect on the server that the user is still connected.


使用javascript超时来调用webservice,然后执行所需的工作.
Use javascript timeout to call webservice, then do job you want.


这篇关于如何停止在ASP.net 2.0中的新线程中运行的Timer的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆