开发者

Timer access Class Field

Is there a开发者_JAVA技巧ny possible way to access the field - str in the Class Program and the variable num - in the main function?

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();
    }
}

Best Regards,


The field just needs to be made static.

static string str = "This is a string";

To access num you need to use a lambda expression.

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

});

You can also use an 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");

});

There is one more option. The System.Threading.Timer class allows you to pass a state object.

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


str should be accessible directly if you change it to static as its implemented now since it is at class level. Num is internal to main and so cannot be accessed unless you pass a reference to it. You can move it external to main, or if its supported in ElapsedEventArgs pass a reference to it and retrieve it that way.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜