System.Threading.Timer.Timer()的最佳重载方法匹配具有一些无效的参数 [英] The best overloaded method match for System.Threading.Timer.Timer() has some invalid arguments

查看:94
本文介绍了System.Threading.Timer.Timer()的最佳重载方法匹配具有一些无效的参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在制作一个控制台应用程序,该应用程序必须在一定的时间间隔内调用某个方法.

I'm making a console application that must call a certain method in timed intervals.

我已经进行了搜索,发现System.Threading.Timer类可以实现这种功能,但是我不太了解如何实现它.

I've searched for that and found that the System.Threading.Timer class can achieve such a functionality, but I'm not quite following how to implement it.

我尝试过:

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);行上看到一条错误消息:

But I get an error on the Timer x = new Timer(test, null, 0, 1000); line that says:

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

The best overloaded method match for System.Threading.Timer.Timer(System.Threading.TimerCallback, object, int, int)' has some invalid arguments

我真的不知道如何使它正常工作,但是如果有人有链接或可以为初学者解释计时器的内容,我将不胜感激.

I really don't know how to make this work properly, but if anyone has a link or something that can explain timers for a beginner, I'd be grateful.

推荐答案

问题是您的test()方法的签名:

The problem is that the signature of your test() method:

public static void test()

TimerCallback所需的签名不匹配:

public delegate void TimerCallback(
    Object state
)

这意味着您不能直接从test方法创建TimerCallback.最简单的操作是更改test方法的签名:

That means you can't create a TimerCallback directly from the test method. The simplest thing to do is to change the signature of your test method:

public static void test(Object state)

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

Or you could use a lambda expression in your constructor call:

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

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

Note that to follow .NET naming conventions, your method name should start with a capital letter, e.g. Test rather than test.

这篇关于System.Threading.Timer.Timer()的最佳重载方法匹配具有一些无效的参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆