2016-04-11 5 views
2

ich die Lösung verwenden zur Verfügung gestellt in: https://stackoverflow.com/a/19104345/2713516 WaitForExit async laufen, aber ich mag die Int32-Parameter Überlast (https://msdn.microsoft.com/en-us/library/ty0d8k56(v=vs.110).aspx) verwenden, wie in process.WaitForExit (10000).process.WaitForExit (int32) asynchron

Wie ändere ich diese Erweiterungsmethode, so dass sie mit dem Timeout-Parameter funktioniert?

Side Frage: Ich sah auch jemand erwähnt (https://stackoverflow.com/a/32994778/2713516), dass ich die CancellationToken irgendwann entsorgt werden darf, sollte ich nicht eine dispose/dann innerhalb der Methode? und wie?

+0

Sie könnten nutzen die ‚kein eingebautes in timeout‘ Muster von http://stackoverflow.com/questions/25683980/timeout: Eine Alternative wäre ein Task.Run mit dem Aufruf an die gewünschten Überlastung wie dies zu tun -pattern-auf-task-based-asynchron-method-in-c-sharp –

+0

Sie geben bereits ein 'CancellationToken' weiter - das ist schon nützlicher als eine Auszeit. Kündigen Sie einfach nach Ablauf der Zeitüberschreitung, z. 'neue CancellationTokenSource (Timeout) .Token'. – Luaan

+0

danke für die Vorschläge – user2713516

Antwort

2

Sie müssen die Methodensignatur ändern und das Ergebnis aus dem Prozess selbst übernehmen. Zum Beispiel ist folgendes zu beachten:

/// <summary> 
/// Waits asynchronously for the process to exit. 
/// </summary> 
/// <param name="process">The process to wait for cancellation.</param> 
/// <param name="cancellationToken">A cancellation token. If invoked, the task will return 
/// immediately as canceled.</param> 
/// <returns>A Task representing waiting for the process to end.</returns> 
public static Task WaitForExitAsync(this Process process, 
    int milliseconds, 
    CancellationToken cancellationToken = default(CancellationToken)) 
{ 
    var tcs = new TaskCompletionSource<object>(); 
    process.EnableRaisingEvents = true; 
    process.Exited += (sender, args) => tcs.TrySetResult(null); 
    if (cancellationToken != default(CancellationToken)) 
    { 
     cancellationToken.Register(tcs.SetCanceled); 
    } 

    return Task.WhenAny(tcs.Task, Task.Delay(milliseconds)); 
} 

Nun, wenn der Prozess die Aufgabe nach der Verzögerung nicht beendet ist noch zurückgegeben werden.

/// <summary> 
/// Waits asynchronously for the process to exit. 
/// </summary> 
/// <param name="process">The process to wait for cancellation.</param> 
/// <param name="cancellationToken">A cancellation token. If invoked, the task will return 
/// immediately as canceled.</param> 
/// <returns>A Task representing waiting for the process to end.</returns> 
public static Task WaitForExitAsync(this Process process, 
    int milliseconds, 
    CancellationToken cancellationToken = default(CancellationToken)) 
{  
    return Task.Run(() => process.WaitForExit(milliseconds), cancellationToken); 
} 
+0

Ich werde mit dem ersten gehen, danke – user2713516

Verwandte Themen