定时器访问类字段

时间:2009-12-16 02:25:42

标签: c# multithreading timer

是否有任何可能的方法来访问字段 - 类程序中的str和主函数中的变量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();
    }
}

最诚挚的问候,

2 个答案:

答案 0 :(得分: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);

答案 1 :(得分:0)

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