简体   繁体   English

调用一个每5秒返回一个值的方法

[英]Call a method that returns a value every 5 seconds

I want to call a method which returns a value every few seconds. 我想调用一个每隔几秒返回一个值的方法。 I have tried using a Timer with elapsedEventandler , but the return type of the method is void in this case. 我已经尝试使用带有elapsedEventandlerTimer ,但在这种情况下,该方法的返回类型是无效的。 I have used the TimerTask class to perform the same task in Java. 我已经使用TimerTask类在Java中执行相同的任务。

I want it to be in .NET 2.0 as I'm using Visual Studio 2005. 我希望它在.NET 2.0中,因为我正在使用Visual Studio 2005。

Below is the program I'm having trouble with. 以下是我遇到麻烦的程序。 I tried to use an anonymous method, but the value of response in this case does not exist outside the anonymous method: 我尝试使用匿名方法,但在这种情况下, response的值不存在于匿名方法之外:

public static string Run(string address)
{                     
    string response = "A";
    Timer t = new Timer();
    t.Elapsed += delegate 
    {                         
        response = callURL(address);
        console.writeln(response);
        // The actual response value is printed here                
    };          
    t.Interval = 3000;
    t.Start();                      
    Console.WriteLine("response string is " + response);
    // response string is A

    return response;
}

public static string callURL(string address)
{
    className sig = new ClassName(); 
    String responseBody = sig.getURL(address);

    return responseBody;
}

How do I get the value of response in the Run method and send it to the caller of the Run method? 我如何获得的值responseRun方法,并将其发送给调用者Run的方法?

You could have your caller give the class with the timer a callback delegate to pass back the value. 您可以让您的调用者为该类提供一个回调委托的计时器以传回该值。

public class YourClass
{
    public static void Run(string address, Action<string> callback)
    {                     
        Timer t = new Timer();
        t.Elapsed += delegate {                         
            var response = callURL(address);

            callback(response);
        };          
        t.Interval = 3000;
        t.Start();
    }
}

public class OtherClass
{
    public void ProcessResponse(string response)
    {
         // do whatever you want here to handle the response...
         // you can write it out, store in a queue, put in a member, etc.
    }

    public void StartItUp()
    {
         YourClass.Run("http://wwww.somewhere.net", ProcessResponse);
    }
}

UPDATE : If you want the caller ( OtherClass ) to be able to cancel the timer, you could simply change from an Action<string> to a Func<string, bool> and have the caller ( OtherClass ) return a bool on whether to stop the timer or not... 更新 :如果您希望调用者( OtherClass )能够取消计时器,您可以简单地从Action<string>更改为Func<string, bool>并让调用者( OtherClass )返回bool是否停止计时器与否......

public class YourClass
{
    public static void Run(string address, Func<string, bool> callback)
    {                     
        Timer t = new Timer();
        t.Elapsed += delegate {                         
            var response = callURL(address);

            // if callback returns false, cancel timer
            if(!callback(response))
            {
                t.Stop();
            }
        };          
        t.Interval = 3000;
        t.Start();
    }
}

public class OtherClass
{
    public bool ProcessResponse(string response)
    {
         // do whatever you want here to handle the response...
         // you can write it out, store in a queue, put in a member, etc.
         // check result to see if it's a certain value...
         // if it should keep going, return true, otherwise return false
    }

    public void StartItUp()
    {
         YourClass.Run("http://wwww.somewhere.net", ProcessResponse);
    }
}

Create a Thread and make the thread call the method you want and give a sleep time to the thread for 5 seconds: 创建一个Thread并让线程调用你想要的方法,并给线程一个休眠时间5秒:

Thread loopThread = new Thread(new ThreadStart(this.MainLoop));
loopThread.Start();

private void MainLoop()
{
     while(true)
     {
         // Do stuff
         Thread.Sleep(5000);
     }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM