【问题标题】:C# Getting return value from Elapsed Time EventC# 从 Elapsed Time 事件中获取返回值
【发布时间】:2013-10-06 13:37:14
【问题描述】:

您好,我有一个与旧线程类似的问题,我仍然无法解决 (Pass a return value back through an EventHandler)。我最终试图实现一个计时器,它将以均匀的间隔计算速度,所以我需要 Elapsed Time 事件返回某种值。我试过使用全局变量,但事件似乎并没有改变变量。有什么建议吗?提前致谢!

namespace Timer_Label
{
public static class GlobalVariables
{
    public static int _stringHolder;

    public static int StringHolder
    {
        get { return _stringHolder; }
        set { _stringHolder = value; }
    }
}

    public partial class Form1 : Form
   {
    public Form1()
    {
        InitializeComponent();

        System.Timers.Timer myTimer = new System.Timers.Timer();
        myTimer.Elapsed += new ElapsedEventHandler(DisplayTimeEvent);
        myTimer.Interval = 500;
        myTimer.Start();


        MessageBox.Show(Convert.ToString(GlobalVariables.StringHolder));
    }

  public static void DisplayTimeEvent(object sender, ElapsedEventArgs e)
    {   
        GlobalVariables.StringHolder = "1";                                 
    }

【问题讨论】:

    标签: c# event-handling return-value elapsedtime


    【解决方案1】:

    在代码到达您的 MessageBox.Show 语句时,计时器已过期的可能性很小。

    尝试在 myTimer.Start() 和 MessageBox.Show() 之间调用 Thread.Sleep(1000)。这应该让计时器有时间过去并执行您的 DisplayTimeEvent 处理程序。

    最终,您需要考虑 System.Timer.Timer 类在后台线程中执行其回调这一事实,因此您在 DisplayTimeEvent 中所做的更改将需要同步。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-10-26
      • 1970-01-01
      • 1970-01-01
      • 2019-05-29
      • 1970-01-01
      • 1970-01-01
      • 2011-07-24
      • 2018-06-30
      相关资源
      最近更新 更多