我想调用一个每隔几秒返回一个值的方法。
我尝试使用Timer
和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;
}
如何在response
方法中获取Run
的值并将其发送给Run
方法的来电者?
答案 0 :(得分: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);
}
}
更新:如果您希望来电者(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);
}
}
答案 1 :(得分:0)
创建一个Thread
并让线程调用你想要的方法,并给线程一个休眠时间5秒钟:
Thread loopThread = new Thread(new ThreadStart(this.MainLoop));
loopThread.Start();
private void MainLoop()
{
while(true)
{
// Do stuff
Thread.Sleep(5000);
}
}