// Scan a range of ports asynchronously public async void ExecuteRangeAsync(string hostname, int portMin, int portMax, int timeout, ScanMode scanMode, MainWindow.ExecuteOnceAsyncCallback callback, CancellationToken ct) { // Instantiate a PortScanner InstantiatePortScanner(scanMode); // Assign first values portScanner.Hostname = hostname; portScanner.Timeout = timeout; bool isLast = false; bool cancelled = false; for (int i = portMin; i <= portMax && !cancelled; i++) { if (i == portMax) { isLast = true; } portScanner.Port = i; var task = portScanner.CheckOpenAsync(ct); await task; cancelled = ct.IsCancellationRequested; callback(i, task.Result, cancelled, isLast); } }
// Scan one port asynchronously public async void ExecuteOnceAsync(string hostname, int port, int timeout, ScanMode scanMode, MainWindow.ExecuteOnceAsyncCallback callback, CancellationToken ct) { // Instantiate a PortScanner InstantiatePortScanner(scanMode); // Assign values portScanner.Hostname = hostname; portScanner.Port = port; portScanner.Timeout = timeout; // Await for the result of this operation var task = portScanner.CheckOpenAsync(ct); await task; // If a cancellation request has been triggered through CancellationToken ct, we must advise the callback function bool cancelled = ct.IsCancellationRequested; // Callback with the result and the port callback(port, task.Result, cancelled, true); }