Tôi cần hủy chức năng UpdateDatabase() nếu mất hơn 2 phút. Tôi đã thử cancellationtokens và giờ nhưng tôi không thể quản lý để giải quyết vấn đề này (không thể tìm thấy bất kỳ ví dụ thích hợp nào).Hủy chức năng không đồng bộ tĩnh với thời gian chờ
Bạn có thể giúp tôi về điều này không?
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
}
Chỉnh sửa lớp học của tôi theo câu trả lời.
App.xaml.cs vẫn giữ nguyên. UpdateDatabase() được chỉnh sửa và mới phương pháp RunUpdate() thêm vào trong LocalStorage.cs:
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
}
Tôi biết đây không phải là cách duy nhất và có thể là tốt hơn nhưng một điểm tốt để bắt đầu cho những người mới như tôi.
bạn có thể sử dụng WaitOne nếu bạn có thể chờ cho đến khi cuộc gọi kết thúc với một thời gian chờ hoặc bạn cần phải thực hiện timer của riêng bạn .. Tham khảo http://stackoverflow.com/questions/5973342/how-to-handle-timeout-in-async-socket –