System.Threading.Timer.Timer()的最佳重载方法匹配具有一些无效参数

时间:2012-12-23 14:44:38

标签: c# .net multithreading timer

我正在制作一个控制台应用程序,它必须以定时间隔调用某个方法。

我已经搜索过了,发现System.Threading.Timer类可以实现这样的功能,但我并没有完全遵循如何实现它。

我试过了:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Threading;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            Timer x = new Timer(test, null, 0, 1000);
            Console.ReadLine();
        }

        public static void test()
        {
            Console.WriteLine("test");
        }
    }
}

但我在Timer x = new Timer(test, null, 0, 1000);行上收到错误消息:

  

System.Threading.Timer.Timer(System.Threading.TimerCallback,object,int,int)的最佳重载方法匹配'有一些无效的参数

我真的不知道如何使这项工作正常,但如果有人有链接或可以为初学者解释计时器的东西,我将不胜感激。

3 个答案:

答案 0 :(得分:15)

问题在于test()方法的签名:

public static void test()

TimerCallback所需的签名不匹配:

public delegate void TimerCallback(
    Object state
)

这意味着您无法直接从TimerCallback方法创建test。最简单的方法是更改​​test方法的签名:

public static void test(Object state)

或者你可以在构造函数调用中使用lambda表达式:

Timer x = new Timer(state => test(), null, 0, 1000);

请注意,要遵循.NET命名约定,您的方法名称应以大写字母开头,例如Test而不是test

答案 1 :(得分:3)

TimerCallback委托(您使用的Timer构造函数的第一个参数)接受object类型的一个参数(状态)。

您只需要将参数添加到test方法

即可
public static void test(object state)
{
    Console.WriteLine("test");
}

问题将得到解决。

答案 2 :(得分:1)

按如下方式编写测试方法以解决异常:

public static void test(object state)
        {
            Console.WriteLine("test");
        }
相关问题