【发布时间】:2013-07-31 21:18:42
【问题描述】:
如果需要超过 2 分钟,我需要取消 UpdateDatabase() 函数。我试过 cancellationtokens 和 timers 但我无法解决这个问题(找不到任何合适的例子)。
您能帮我解决这个问题吗?
App.xaml.cs
protected override async void OnLaunched(LaunchActivatedEventArgs args)
{
await PerformDataFetch();
}
internal async Task PerformDataFetch()
{
await LocalStorage.UpdateDatabase();
}
LocalStorage.cs
public async static Task<bool> UpdateDatabase()
{
await ..// DOWNLOAD FILES
await ..// CHECK FILES
await ..// RUN CONTROLES
}
根据答案编辑了我的课程。
App.xaml.cs 保持不变。 UpdateDatabase() 被编辑并在 LocalStorage.cs 中添加了新方法 RunUpdate():
public static async Task UpdateDatabase()
{
CancellationTokenSource source = new CancellationTokenSource();
source.CancelAfter(TimeSpan.FromSeconds(30)); // how much time has the update process
Task<int> task = Task.Run(() => RunUpdate(source.Token), source.Token);
await task;
}
private static async Task<int> RunUpdate(CancellationToken cancellationToken)
{
cancellationToken.ThrowIfCancellationRequested();
await ..// DOWNLOAD FILES
cancellationToken.ThrowIfCancellationRequested();
await ..// CHECK FILES
cancellationToken.ThrowIfCancellationRequested();
await ..// RUN CONTROLES
}
我知道这不是唯一的方法,而且可能会更好,但对于像我这样的新手来说,这是一个很好的起点。
【问题讨论】:
-
如果您可以等到通话超时结束或者您需要实现自己的计时器,则可以使用 WaitOne。请参阅stackoverflow.com/questions/5973342/…
标签: c# windows-runtime microsoft-metro c#-5.0 winrt-async