public static AsyncRequestObject GetIPAddressTask(string hostAddress, OnGetIPAddressComplete GetIPAddressCompleteCallback, CancellationTokenSource cts = null, TaskScheduler ts = null) { AsyncRequestObject aro = new AsyncRequestObject(cts); aro.task = Task.Factory.StartNew(() => { return(GetIPAddress(hostAddress, aro.CancellationToken)); }, aro.CancellationToken, TaskCreationOptions.None, TaskScheduler.Default).ContinueWith((antecedent) => { if (!aro.CancellationToken.IsCancellationRequested) { switch (antecedent.Status) { case TaskStatus.Faulted: if (GetIPAddressCompleteCallback != null) { GetIPAddressCompleteCallback(antecedent.Exception.InnerException, aro); } break; case TaskStatus.RanToCompletion: if (GetIPAddressCompleteCallback != null) { GetIPAddressCompleteCallback(antecedent.Result, aro); } break; } } }, ts == null ? TaskScheduler.FromCurrentSynchronizationContext() : ts); return(aro); }
public static AsyncRequestObject TCPRequestPulseRequestsTask(PeerAddress host, byte[] pkt1, byte[] pkt2, int msDelay, OnTCPRequestComplete TCPRequestCompleteCallback, CancellationTokenSource cts = null, TaskScheduler ts = null) { AsyncRequestObject aro = new AsyncRequestObject(cts); aro.task = Task.Factory.StartNew(() => { if (host.ipAddress == null) { throw new Exception("No IP Address"); // Not a good idea // host.ipAddress = GetIPAddress(host.address, aro.CancellationToken); } Socket socket = ConnectTCP(host.ipAddress, host.port, aro.CancellationToken); TransmitOnSocket(socket, pkt1, aro.CancellationToken); }, aro.CancellationToken, TaskCreationOptions.None, TaskScheduler.Default).ContinueWith((antecedent) => { aro.CancellationToken.WaitHandle.WaitOne(msDelay); aro.CancellationToken.ThrowIfCancellationRequested(); Socket socket = ConnectTCP(host.ipAddress, host.port, aro.CancellationToken); TransmitOnSocket(socket, pkt2, aro.CancellationToken); }, aro.CancellationToken).ContinueWith((antecedent) => { if (!aro.CancellationToken.IsCancellationRequested) { switch (antecedent.Status) { case TaskStatus.Faulted: aro.exception = antecedent.Exception.InnerException; if (TCPRequestCompleteCallback != null) { TCPRequestCompleteCallback(antecedent.Exception.InnerException, aro); } break; case TaskStatus.RanToCompletion: if (TCPRequestCompleteCallback != null) { TCPRequestCompleteCallback(null, aro); } break; } } }, ts == null ? TaskScheduler.FromCurrentSynchronizationContext() : ts); return(aro); }