简体   繁体   English

C# 取消订阅计时器事件不起作用

[英]C# unsubscribe from timer event not working

[Inject]
public Timer timer { get; set; }

protected override void OnInitialized()
{
    settingsModel = applicationDb.SettingsModal.FirstOrDefault();
    updateInfo();
}

public async void updateInfo()
{
    try
    {
        if (settingsModel.Message != "" && settingsModel.Message != null)
        {
            timer.Elapsed -= (w, e) => timer_Elapsed(w,e);
            timer.Elapsed += (w, e) => timer_Elapsed(w, e);          
            timer.Interval = 3000;
            timer.Start();
        }
        else
        {
            timer.Elapsed -= (w, e) => timer_Elapsed(w, e);

            timer.Stop();
        }
    }
    catch (Exception e)
    {
        ToastService.ShowError(e.Message);
    }
}

async void timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
{       
    // do some stuff
}

The problem is unsubscribe not working on this line问题是取消订阅在这条线上不起作用

timer.Elapsed -= new System.Timers.ElapsedEventHandler(timer_Elapsed);

Each time the UpdateInfo method gets called, the event timer.Elapsed gets more sub每次调用UpdateInfo方法时,事件timer.Elapsed都会获得更多子

Subscribe to the method instead of an anonymous function.订阅该方法而不是匿名 function。

// Subscribe
timer.Elapsed += timer_Elapsed; 

// Unsubscribe
timer.Elapsed -= timer_Elapsed;

From this page on subscribing to events .从这个页面订阅事件

If you don't have to unsubscribe from an event later, you can use the addition assignment operator (+=) to attach an anonymous function as an event handler.如果以后不必取消订阅某个事件,则可以使用加法赋值运算符 (+=) 附加匿名 function 作为事件处理程序。

You cannot easily unsubscribe from an event if you used an anonymous function to subscribe to it.如果您使用匿名 function 订阅活动,则无法轻松取消订阅。

We recommend that you don't use anonymous functions to subscribe to events if you have to unsubscribe from the event at some later point in your code.如果您稍后必须在代码中取消订阅事件,我们建议您不要使用匿名函数来订阅事件。

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

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