繁体   English   中英

委托在C#中不起作用

[英]delegate does not work in c#

有谁知道为什么控制即使被调用也永远不会到达委托人? 无论我是否逐步调试,它都不会到达那里。

public void UpdateClock()
{
    //control never gets here 
}

delegate void UpdateClockDelegate();    

private void MT_TimerTick(object source, ElapsedEventArgs e)
{
    if (InvokeRequired) 
    { 
        //control gets here, but does not invoke, apparently
        Invoke(new UpdateClockDelegate(UpdateClock)); 
    }
}

我根据以下链接中的说明建立了该解决方案

InvokeInvokeRequired通常用于确保在UI线程上执行功能。 它通常会自行调用,而不是其他功能。

您的代码可能如下所示:

public void UpdateClock()
{
    ...
}

private void MT_TimerTick(object source, ElapsedEventArgs e)
{
    if (InvokeRequired) 
    { 
        Invoke(new Action<object, ElapsedEventArgs>(TimerTick), source, e); 
    }
    else
    {
        UpdateClock();
    }
}

此外,我同意Scorpi0使用System.Windows.Forms.Timer,它将始终自动在UI线程上触发事件。

我认为您正在混合System.Timers.TimerSystem.Windows.Forms.Timer

  • System.Timers.Timer :该事件称为Elapsed ,它需要一个ElapsedEventArgs
  • System.Windows.Forms.Timer :该事件称为Tick ,它需要一个EventArgs

如我所见,签名

MT_TimerTick(object source, ElapsedEventArgs e) 

发出警报。
应该是

MT_TimerElapsed(object source, ElapsedEventArgs e)

要么

MT_TimerTick(object source, EventArgs e)

检查您使用的是好的,并且您的活动已订阅。

-对于System.Timers.Timer

 MT_Timer.Elapsed += new ElapsedEventHandler(MT_Timer_Elapsed);
 MT_Timer.Start();
 void MT_Timer_Elapsed(object sender, ElapsedEventArgs e) { }

-对于System.Windows.Forms.Timer

MT_Timer.Tick += new EventHandler(MT_Timer_Tick);
MT_Timer.Start();
void MT_Timer_Tick(object sender, EventArgs e) { }

试试这个,希望它可以帮助您...

public void UpdateClock()
{
    this.MT_TimerTickCompleted += delegate(object sender, ElapsedEventArgs e)
    {
        //When MT_TimerTick occur, do something
    };
}

delegate void UpdateClockDelegate();    

private void MT_TimerTick(object source, ElapsedEventArgs e)
{
    if (InvokeRequired) 
    { 
        MT_TimerTickNotify(object, e); 
    }
}

public event EventHandler MT_TimerTickCompleted;
private void MT_TimerTickNotify(object sender, ElapsedEventArgs e)
{
    if (MT_TimerTickCompleted != null)
        MT_TimerTickCompleted(sender, e);
}

暂无
暂无

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

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