2013-07-31 12 views
7

Devo annullare la funzione UpdateDatabase() se impiega più di 2 minuti. Ho provato cancellationtokens e timer ma non sono riuscito a risolvere questo (non ho trovato alcun esempio appropriato).Annulla una funzione asincrona statica con un timeout

Potrebbe aiutarmi per favore su questo?

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 
} 

A cura le mie lezioni in base alle risposte.

App.xaml.cs rimane uguale. UpdateDatabase() viene modificato e il nuovo metodo RunUpdate() aggiunto in 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 
} 

So che questo non è l'unico modo e poteva essere migliore, ma un buon punto di partenza per neofiti come me.

+0

è possibile utilizzare WaitOne se si può aspettare fino a quando la chiamata si conclude con un timeout o avete bisogno di implementare il proprio timer .. Fare riferimento http://stackoverflow.com/questions/5973342/how-to-handle-timeout-in-async-socket –

risposta

5

È necessario passare unalla funzione UpdateDatabase e controllare il token dopo ogni attesa chiamando lo ThrowIfCancellationRequested. Vedi this

+2

Inoltre, passare il token a ciascun metodo chiamato che prende un token. –

1

si potrebbe provare questo:

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