Kor*_*kig 7 c# c#-5.0 microsoft-metro windows-runtime winrt-async
如果需要超过2分钟,我需要取消UpdateDatabase()函数.我已经尝试过canceltokens和计时器,但我无法解决这个问题(找不到任何合适的例子).
你能帮帮我吗?
App.xaml.cs
protected override async void OnLaunched(LaunchActivatedEventArgs args)
{
await PerformDataFetch();
}
internal async Task PerformDataFetch()
{
await LocalStorage.UpdateDatabase();
}
Run Code Online (Sandbox Code Playgroud)
LocalStorage.cs
public async static Task<bool> UpdateDatabase()
{
await ..// DOWNLOAD FILES
await ..// CHECK FILES
await ..// RUN CONTROLES
}
Run Code Online (Sandbox Code Playgroud)
根据答案编辑我的课程.
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
}
Run Code Online (Sandbox Code Playgroud)
我知道这不是唯一的方法,可能会更好,但对于像我这样的新手来说,这是一个很好的开始.