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

Bha*_*ath 3 c# c#-2.0

我想调用一个每隔几秒返回一个值的方法.我尝试过使用Timerwith elapsedEventandler,但在这种情况下,方法的返回类型是无效的.我已经使用TimerTask该类在Java中执行相同的任务.

我希望它在.NET 2.0中,因为我正在使用Visual Studio 2005.

以下是我遇到麻烦的程序.我试图使用匿名方法,但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;
}
Run Code Online (Sandbox Code Playgroud)

我如何获得的值response的Run方法,并将其发送给调用者Run的方法?

Jam*_*are 8

您可以让您的调用者为该类提供一个回调委托的计时器以传回该值.

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);
    }
}
Run Code Online (Sandbox Code Playgroud)

更新:如果你想让调用者(OtherClass)能够取消定时器,你可以简单地从Action<string>a 更改为a 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);
    }
}
Run Code Online (Sandbox Code Playgroud)