下面是我想到的。
SmartDispatcherTimer
延伸DispatcherTimer
(是讓這件事最簡單的方式和運行)
- 擁有
TickTask
屬性來提供一個Task
處理邏輯
- 有一個
IsReentrant
屬性(當然整個的一點是,我希望它不可重入,所以通常這是錯誤的)
- 它假設你所說的任何事情都是完全可以等待的 - 或者你最終失去了重入保護的好處
用法:
var timer = new SmartDispatcherTimer();
timer.IsReentrant = false;
timer.Interval = TimeSpan.FromSeconds(30);
timer.TickTask = async() =>
{
StatusMessage = "Updating..."; // MVVM property
await UpdateSystemStatus(false);
StatusMessage = "Updated at " + DateTime.Now;
};
timer.Start();
下面的代碼。想聽聽任何想法
public class SmartDispatcherTimer : DispatcherTimer
{
public SmartDispatcherTimer()
{
base.Tick += SmartDispatcherTimer_Tick;
}
async void SmartDispatcherTimer_Tick(object sender, EventArgs e)
{
if (TickTask == null)
{
Debug.WriteLine("No task set!");
return;
}
if (IsRunning && !IsReentrant)
{
// previous task hasn't completed
Debug.WriteLine("Task already running");
return;
}
try
{
// we're running it now
IsRunning = true;
Debug.WriteLine("Running Task");
await TickTask.Invoke();
Debug.WriteLine("Task Completed");
}
catch (Exception)
{
Debug.WriteLine("Task Failed");
}
finally
{
// allow it to run again
IsRunning = false;
}
}
public bool IsReentrant { get; set; }
public bool IsRunning { get; private set; }
public Func<Task> TickTask { get; set; }
}
你看過'Task.Delay()'嗎? – svick
@svick不太清楚你的意思,除非你在談論某種類型的無限循環,但接下來會在哪裏運行 –
是的,我的意思是像無限循環。如果你從UI線程「等待」它,那麼它也會在那裏恢復。你可以從'async void'方法調用它,這意味着它將獨立於調用它的代碼運行。 – svick