public static bool CallUrl(string url, DownloadStringCompletedEventHandler handler, TimeoutContext tc) { WebClient wc = new WebClient(); // wc.Headers[HttpRequestHeader.IfModifiedSince] = DateTime.UtcNow.ToString(CultureInfo.InvariantCulture); if (handler != null) { wc.DownloadStringCompleted += handler; } Uri uri = null; try { uri = new Uri(url); } catch (FormatException) { return(false); } wc.DownloadStringAsync(uri, tc); if (tc != null) { wc.DownloadProgressChanged += tc.wc_DownloadProgressChanged; tc.Tag = wc; ThreadPool.QueueUserWorkItem( (obj) => { TimeoutContext timeContext = obj as TimeoutContext; if (timeContext == null) { return; } WebClient wcInProgress = timeContext.Tag as WebClient; if (wcInProgress == null) { return; } Thread.Sleep(timeContext.Timeout); if (timeContext.Connected == true) { return; } if (timeContext.Completed == false) { wcInProgress.CancelAsync(); } }, tc); } return(true); }
public static bool CallUrl(string url, DownloadStringCompletedEventHandler handler, TimeoutContext tc) { WebClient wc = new WebClient(); // wc.Headers[HttpRequestHeader.IfModifiedSince] = DateTime.UtcNow.ToString(CultureInfo.InvariantCulture); if (handler != null) { wc.DownloadStringCompleted += handler; } Uri uri = null; try { uri = new Uri(url); } catch (FormatException) { return false; } wc.DownloadStringAsync(uri, tc); if (tc != null) { wc.DownloadProgressChanged += tc.wc_DownloadProgressChanged; tc.Tag = wc; ThreadPool.QueueUserWorkItem( (obj) => { TimeoutContext timeContext = obj as TimeoutContext; if (timeContext == null) { return; } WebClient wcInProgress = timeContext.Tag as WebClient; if (wcInProgress == null) { return; } Thread.Sleep(timeContext.Timeout); if (timeContext.Connected == true) { return; } if (timeContext.Completed == false) { wcInProgress.CancelAsync(); } }, tc); } return true; }
void btnConnect_Click(object sender, EventArgs e) { string url = string.Format("http://{0}:{1}/getSnapshot", txtIP.Text, txtPort.Text); TimeoutContext tc = new TimeoutContext(); tc.Timeout = 5000; if (App.CallUrl(url, SnapshotCompleted, tc) == true) { EnableControls(false); } }
private void btnConnectClicked(object sender, RoutedEventArgs e) { string url = string.Format("http://{0}:{1}/getSnapshot", this.Application.IPSelected, this.Application.Port); TimeoutContext tc = new TimeoutContext(); tc.Timeout = 5000; if (App.CallUrl(url, SnapshotCompleted, tc) == true) { EnableControls(false); } }