摘要:將工作丟至背景反覆執行 Background.Repeat(...)
class Background
{
public static void Repeat(Action action, Func keepRunning)
{
new Background(action, keepRunning);
}
public static void Execute(Action action)
{
new Background(action, null);
}
private readonly Action _action;
private readonly Func _keepRunning;
private Background(Action action, Func keepRunning)
{
_action = action;
_keepRunning = keepRunning;
_action.BeginInvoke(EndInvoke, this);
}
private void EndInvoke(IAsyncResult ar)
{
_action.EndInvoke(ar);
if (_keepRunning != null && _keepRunning())
_action.BeginInvoke(EndInvoke, this);
}
}
class Program
{
static void Main(string[] args)
{
var keepRunning = true;
//Background.Execute(() => Test("Q"));
//Background.Execute(() => Test("A"));
//Background.Execute(() => Test("Z"));
Background.Repeat(() => Test("Q"), () => keepRunning);
Background.Repeat(() => Test("A"), () => keepRunning);
Background.Repeat(() => Test("Z"), () => keepRunning);
Console.ReadKey(true);
keepRunning = false;
Console.ReadKey(true);
}
static void Test(string id)
{
for (int i = 0; i < 5; i++)
{
Console.WriteLine("{2} ({0}/5) {1}", i + 1, DateTime.Now, id);
Thread.Sleep(1000);
}
}
}