【问题标题】:Timer access Class Field定时器访问类字段
【发布时间】:2009-12-16 02:25:42
【问题描述】:

有什么方法可以访问类程序中的字段 str 和 main 函数中的变量 num 吗?

class Program
{
    string str = "This is a string";
    static void Main(string[] args)
    {
        int num = 100;
        Debug.WriteLine(Thread.CurrentThread.ManagedThreadId);
        var timer = new System.Timers.Timer(10000);
        timer.Elapsed += new ElapsedEventHandler(timer_Elapsed);
        timer.Start();
        for (int i = 0; i < 20; i++)
        {
            Debug.WriteLine(Thread.CurrentThread.ManagedThreadId + " " + "current I is " + i.ToString());
            Thread.Sleep(1000);
        }
        Console.ReadLine();
    }

    static void timer_Elapsed(object sender, ElapsedEventArgs e)
    {
        Debug.WriteLine(str);
        Debug.WriteLine(num);
        Debug.WriteLine(Thread.CurrentThread.ManagedThreadId + "  current is timer");
        //throw new NotImplementedException();
    }
}

最好的问候,

【问题讨论】:

    标签: c# multithreading timer


    【解决方案1】:

    该字段只需设为static

    static string str = "This is a string";
    

    要访问num,您需要使用lambda expression

    timer.Elapsed += new ElapsedEventHandler((s, e) =>
    {
         Debug.WriteLine(str);
         Debug.WriteLine(num);
         Debug.WriteLine(Thread.CurrentThread.ManagedThreadId + "  current is timer");
    
    });
    

    您也可以使用anonymous method

    timer.Elapsed += new ElapsedEventHandler(delegate(object sender, ElapsedEventArgs e)
    {
         Debug.WriteLine(str);
         Debug.WriteLine(num);
         Debug.WriteLine(Thread.CurrentThread.ManagedThreadId + "  current is timer");
    
    });
    

    还有一种选择。 System.Threading.Timer 类允许您传递状态对象。

    var timer = new System.Threading.Timer((state) =>
    {
         Debug.WriteLine(str);
         Debug.WriteLine(state);
         Debug.WriteLine(Thread.CurrentThread.ManagedThreadId + "  current is timer");
    }, num, 10000, 10000);
    

    【讨论】:

    【解决方案2】:

    str 应该可以直接访问,如果您将其更改为静态,因为它现在已实现,因为它处于类级别。 Num 在 main 内部,因此除非您传递对它的引用,否则无法访问。您可以将它移到 main 外部,或者如果 ElapsedEventArgs 支持它,则传递对它的引用并以这种方式检索它。

    【讨论】:

    • 刚刚检查过,看起来 ElapsedEventArgs 没有对象来保持状态。您将需要提供全局引用(将 num 移动到类级别)或提供可以使用委托或类似方法访问它的引用指针。
    猜你喜欢
    • 2018-09-08
    • 1970-01-01
    • 2011-07-02
    • 2012-07-10
    • 2018-10-27
    • 2021-09-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多