2013-07-31 50 views
7

Tôi cần hủy chức năng UpdateDatabase() nếu mất hơn 2 phút. Tôi đã thử cancellationtokensgiờ 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.

+0

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 –

Trả lời

5

Bạn cần chuyển một số CancellationToken đến hàm UpdateDatabase và kiểm tra mã thông báo sau mỗi lần chờ bằng cách gọi ThrowIfCancellationRequested. Xem this

+2

Ngoài ra, chuyển mã thông báo cho từng phương thức mà bạn gọi có mã thông báo. –

1

Bạn có thể thử này:

const int millisecondsTimeout = 2500; 
Task updateDatabase = LocalStorage.UpdateDatabase(); 
if (await Task.WhenAny(updateDatabase, Task.Delay(millisecondsTimeout)) == updateDatabase) 
{ 
    //code 
} 
else 
{ 
    //code 
}