Use an array from main in a timer method

时间:2016-11-02 16:32:27

标签: c# arrays timer console-application class-method

I'm working in a Console Application and I want to output the value of an array that exist in the main method inside a timer method. I however have no idea how to send the array values to the timer method as the constructor only takes 4 arguments.

    static void Main(string[] args)
    {
        int[] numbers = new int[7] {1, 2, 3, 4, 5, 6, 7};

        Timer t = new Timer(TimerOutput, 8, 0, 2000);
        Thread.Sleep(10000);
        t.Dispose();

        Console.ReadLine();
    }
    private static void TimerOutput(Object state)
    {
        Console.WriteLine(""); // Here I want to putput the values of numbers[7] from main
        Thread.Sleep(1000);
    }

1 个答案:

答案 0 :(得分:1)

使数组成为Program类的静态属性。然后事件处理程序可以访问它:

private static int[] numbers;

static void Main(string[] args)
{
    numbers = new int[7] {1, 2, 3, 4, 5, 6, 7};

    Timer t = new Timer(TimerOutput, 8, 0, 2000);
    Thread.Sleep(10000);
    t.Dispose();

    Console.ReadLine();
}
private static void TimerOutput(Object state)
{
    // numbers is available in this method.
    Console.WriteLine(""); 
    Thread.Sleep(1000);
}