当前位置: 首页>>代码示例>>C#>>正文


C# WebClient.CancelAsync方法代码示例

本文整理汇总了C#中System.Net.WebClient.CancelAsync方法的典型用法代码示例。如果您正苦于以下问题:C# WebClient.CancelAsync方法的具体用法?C# WebClient.CancelAsync怎么用?C# WebClient.CancelAsync使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在System.Net.WebClient的用法示例。


在下文中一共展示了WebClient.CancelAsync方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。

示例1: ExecuteWebRequest

        private void ExecuteWebRequest(string url, Action<string> callback, Action<Exception> error)
        {
            WebClient webClient = new WebClient();

              // create a timeout timer
              Timer timer = null;
              TimerCallback timerCallback = state =>
              {
            timer.Dispose();
            webClient.CancelAsync();
            error(new TimeoutException());
              };
              timer = new Timer(timerCallback, null, 5000, 5000);

              // create a web client
              webClient.DownloadStringCompleted += (s, e) =>
              {
            timer.Dispose();
            try
            {
              string result = e.Result;
              _marshal.Invoke(() => callback(result));
            }
            catch (Exception ex)
            {
              _marshal.Invoke(() => error(ex));
            }
              };

              webClient.DownloadStringAsync(new Uri(url));
        }
开发者ID:AlexanderGrant1,项目名称:PropertyCross,代码行数:31,代码来源:JsonWebPropertySearch.cs

示例2: DownloadFile

 public Task<Stream> DownloadFile(Uri url)
 {
     var tcs = new TaskCompletionSource<Stream>();
     var wc = new WebClient();
     wc.OpenReadCompleted += (s, e) =>
     {
         if (e.Error != null)
         {
             tcs.TrySetException(e.Error);
             return;
         }
         else if (e.Cancelled)
         {
             tcs.TrySetCanceled();
             return;
         }
         else tcs.TrySetResult(e.Result);
     };
     wc.OpenReadAsync(url);
     MessageBoxResult result = MessageBox.Show("Started downloading media. Do you like to stop the download ?", "Purpose Color", MessageBoxButton.OKCancel);
     if( result == MessageBoxResult.OK )
     {
         progress.HideProgressbar();
         wc.CancelAsync();
         return null;
     }
     return tcs.Task;
 }
开发者ID:praveenmohanmm,项目名称:PurposeColor_Bkp_Code,代码行数:28,代码来源:WinMediaDownloader.cs

示例3: Defaults

		public void Defaults ()
		{
			WebClient wc = new WebClient ();
			CheckDefaults (wc);
			// does nothing if no async operation is in progress
			wc.CancelAsync ();
		}
开发者ID:shana,项目名称:moon,代码行数:7,代码来源:WebClientTest.cs

示例4: ExecuteWebRequest

        private void ExecuteWebRequest(string url, Action<string> callback, Action<Exception> error)
        {
            DispatcherTimer timer = new DispatcherTimer();

              // create a web client to fetch the URL results
              WebClient webClient = new WebClient();
              webClient.DownloadStringCompleted += (s, e) =>
              {
            timer.Stop();
            try
            {
              string result = e.Result;
              callback(result);
            }
            catch (Exception ex)
            {
              error(ex);
            }
              };

              // initiate the download
              webClient.DownloadStringAsync(new Uri(url));

              // create a timeout timer
              timer.Interval = TimeSpan.FromSeconds(5);
              timer.Start();
              timer.Tick += (s, e) =>
            {
              timer.Stop();
              webClient.CancelAsync();
              error(new TimeoutException());
            };
        }
开发者ID:AlexanderGrant1,项目名称:PropertyCross,代码行数:33,代码来源:JsonWebPropertySearch.cs

示例5: DownloadFile

        private void DownloadFile()
        {
            WebClient client = new WebClient();
            //register download events
            client.DownloadProgressChanged += client_DownloadProgressChanged;
            client.DownloadFileCompleted += client_DownloadFileCompleted;
            //start the download
            client.DownloadFileAsync(address, outFileName);

            patchDownloadState = DownloadState.InProgress;
            bool patchDownloadCancelling = false;

            //wait for the file to be downloaded
            while (patchDownloadState == DownloadState.InProgress)
            {
                if (!patchDownloadCancelling && (Cancelling || Cancelled))
                {
                    Description = Messages.DOWNLOAD_AND_EXTRACT_ACTION_DOWNLOAD_CANCELLED_DESC;
                    client.CancelAsync();
                    patchDownloadCancelling = true;
                }
                Thread.Sleep(SLEEP_TIME);
            }

            //deregister download events
            client.DownloadProgressChanged -= client_DownloadProgressChanged;
            client.DownloadFileCompleted -= client_DownloadFileCompleted;

            if (patchDownloadState == DownloadState.Cancelled)
                throw new CancelledException();

            if (patchDownloadState == DownloadState.Error)
                MarkCompleted(patchDownloadError ?? new Exception(Messages.ERROR_UNKNOWN));
        }
开发者ID:aaroneg,项目名称:xenadmin,代码行数:34,代码来源:DownloadAndUnzipXenServerPatchAction.cs

示例6: DownloadVersionInfoTaskAsync

		public async Task<IEnumerable<VersionDescription>> DownloadVersionInfoTaskAsync(
			Uri source,
			CancellationToken cancel_token)
		{
			var client = new WebClient();
			cancel_token.Register(() => client.CancelAsync());
			return ParseAppCast(
				System.Text.Encoding.UTF8.GetString(
					await this.client.DownloadDataTaskAsync(source)));
		}
开发者ID:kumaryu,项目名称:peercaststation,代码行数:10,代码来源:AppCastReader.cs

示例7: WebClientAsync

 public static void WebClientAsync(WebClient client, string url)
 {
     if (client.IsBusy)
         client.CancelAsync();
     try
     {
         client.DownloadStringAsync(new Uri(url, UriKind.Absolute));
     }
     catch (Exception)
     {
     }
 }
开发者ID:vicalloy,项目名称:lb.ting,代码行数:12,代码来源:Utils.cs

示例8: PerformExtractPHP

        private void PerformExtractPHP(Action onComplete)
        {
            SetProgress("Detecting PHP...");

            if (Directory.Exists("C:\\PHP"))
            {
                SetProgress("C:\\PHP already exists.  Assuming PHP is installed (continuing in 2 seconds).");
                Thread.Sleep(2000);
                onComplete();
                return;
            }
            else
            {
                SetProgress("Downloading PHP package...");
                var client = new WebClient();
                client.DownloadProgressChanged += (sender, e) =>
                {
                    if (_installThread == null)
                        client.CancelAsync();
                    SetProgress("Downloading PHP package (" + e.ProgressPercentage + "% complete)...");
                };
                client.DownloadFileCompleted += (sender, e) =>
                {
                    if (_installThread == null)
                        return;
                    SetProgress("Extracting PHP package...");
                    var zip = new ZipFile(Path.Combine(Path.GetTempPath(), "PHP.zip"));
                    Directory.CreateDirectory("C:\\PHP");
                    foreach (ZipEntry entry in zip)
                    {
                        if (!entry.IsFile)
                            continue;

                        var entryFileName = entry.Name;
                        var buffer = new byte[4096];
                        var zipStream = zip.GetInputStream(entry);
                        String fullZipToPath = Path.Combine("C:\\PHP", entryFileName);
                        string directoryName = Path.GetDirectoryName(fullZipToPath);
                        if (directoryName.Length > 0)
                            Directory.CreateDirectory(directoryName);
                        using (var streamWriter = File.Create(fullZipToPath))
                            StreamUtils.Copy(zipStream, streamWriter, buffer);
                    }

                    if (_installThread != null)
                        onComplete();
                };
                client.DownloadFileAsync(
                    new Uri("http://windows.php.net/downloads/releases/php-5.4.14-nts-Win32-VC9-x86.zip"),
                    Path.Combine(Path.GetTempPath(), "PHP.zip"));
            }
        }
开发者ID:hach-que,项目名称:gitextensions,代码行数:52,代码来源:InstallArcanistForm.cs

示例9: PostToImgur

 public void PostToImgur(string filename)
 {
     changeValueEnabled();
     Bitmap bitmap = new Bitmap(filename);
     MemoryStream memoryStream = new MemoryStream();
     bitmap.Save(memoryStream, ImageFormat.Jpeg);
     using (var w = new WebClient()) {
         w.UploadProgressChanged += new UploadProgressChangedEventHandler(delegate(object send, UploadProgressChangedEventArgs arg) {
                 int percent = arg.ProgressPercentage;
                 progressBar.Value = percent > 0 ? (percent < 45 ? percent * 2 : (percent >= 90 ? percent : 90)) : 0;
             });
         this.FormClosing += new FormClosingEventHandler(delegate(object send, FormClosingEventArgs arg) {
                 w.CancelAsync();
             });
         var values = new NameValueCollection
         {
             { "key", IMGUR_API_KEY },
             { "image", Convert.ToBase64String(memoryStream.ToArray()) }
         };
         string debug = values.ToString();
         byte[] response = new byte[0];
         w.UploadValuesCompleted += new UploadValuesCompletedEventHandler(delegate(object send, UploadValuesCompletedEventArgs arg) {
             if (arg.Cancelled) return;
             response = arg.Result;
             XDocument xDocument = XDocument.Load(new MemoryStream(response).ToString());
             bitmap.Dispose();
             _address = (string)xDocument.Root.Element("original_image");
             this.Close();
         });
         w.UploadValuesAsync(new Uri("http://imgur.com/api/upload.xml"), values);
         buttonClose.Click -= buttonClose_Click;
         buttonClose.Click += new EventHandler(delegate(object send, EventArgs arg) {
                 w.CancelAsync();
                 changeValueEnabled();
                 buttonClose.Click += buttonClose_Click;
             });
     }
 }
开发者ID:ulmic,项目名称:MIC_Enterprise,代码行数:38,代码来源:SelectImage.cs

示例10: Execute

        /// <summary>
        /// Starts the video download.
        /// </summary>
        /// <exception cref="IOException">The video file could not be saved.</exception>
        /// <exception cref="WebException">An error occured while downloading the video.</exception>
        public override void Execute()
        {
            // We need a handle to keep the method synchronously
            var handle = new ManualResetEvent(false);
            var client = new WebClient();
            bool isCanceled = false;

            client.DownloadFileCompleted += (sender, args) =>
            {
                handle.Close();
                client.Dispose();

                // DownloadFileAsync passes the exception to the DownloadFileCompleted event, if one occurs
                if (args.Error != null && !args.Cancelled)
                {
                    throw args.Error;
                }

                handle.Set();
            };

            client.DownloadProgressChanged += (sender, args) =>
            {
                var progressArgs = new ProgressEventArgs(args.ProgressPercentage);

                // Backwards compatibility
                this.OnProgressChanged(progressArgs);

                if (this.DownloadProgressChanged != null)
                {
                    this.DownloadProgressChanged(this, progressArgs);

                    if (progressArgs.Cancel && !isCanceled)
                    {
                        isCanceled = true;
                        client.CancelAsync();
                    }
                }
            };

            this.OnDownloadStarted(EventArgs.Empty);

            client.DownloadFileAsync(new Uri(this.Video.DownloadUrl), this.SavePath);

            handle.WaitOne();

            this.OnDownloadFinished(EventArgs.Empty);
        }
开发者ID:nolivierdevelopment,项目名称:YoutubeExtractor,代码行数:53,代码来源:VideoDownloader.cs

示例11: DownloadInstaller

        public string DownloadInstaller(Control aOwner, Version aVersion)
        {
            WebClient Client = new WebClient();
            Client.DownloadProgressChanged += new DownloadProgressChangedEventHandler(Client_DownloadProgressChanged);
            Client.DownloadFileCompleted += new AsyncCompletedEventHandler(Client_DownloadFileCompleted);

            string destinationPath = Path.Combine(Path.GetTempPath(), string.Format("FlySightViewer-{0}-setup.exe", aVersion));
            Uri downloadUrl = new Uri(string.Format("http://tomvandijck.com/flysight/FlySightViewer-{0}-setup.exe", aVersion));

            Client.DownloadFileAsync(downloadUrl, destinationPath);

            if (ShowDialog(aOwner) == System.Windows.Forms.DialogResult.OK)
            {
                return destinationPath;
            }

            Client.CancelAsync();
            return null;
        }
开发者ID:helgef,项目名称:flysight,代码行数:19,代码来源:DownloadDialog.cs

示例12: GetWebClient

        private WebClient GetWebClient(CancellationToken cancelToken, IProgress<DownloadProgressChangedEventArgs> progress)
        {
            var wc = new WebClient
                     {
                         BaseAddress = BaseAddress,
                         CachePolicy = CachePolicy,
                         UseDefaultCredentials = UseDefaultCredentials,
                         Credentials = Credentials,
                         Headers = Headers,
                         Proxy = Proxy
                     };

            if (!string.IsNullOrEmpty(ApiKey)) wc.QueryString["key"] = ApiKey;

            if (cancelToken != CancellationToken.None) cancelToken.Register(() => wc.CancelAsync());
            if (progress != null) wc.DownloadProgressChanged += (sender, args) => progress.Report(args);

            return wc;
        }
开发者ID:dreampet,项目名称:redmine-net-api,代码行数:19,代码来源:RedmineAsyncWebClient.cs

示例13: Form1

        public Form1()
        {
            InitializeComponent();
            client = new WebClient();

            client.Disposed +=
            (s, e) =>
            {
                DownloadBar.Value = 0;
                client.CancelAsync();
                while (client.IsBusy) ;
                try
                {
                    if (File.Exists(this.tbFile.Text))
                        File.Delete(this.tbFile.Text);
                }
                catch(Exception ex)
                {
                    /*FAIL!*/
                }
                this.btBrowse.Enabled = true;
                this.btDownload.Enabled = true;
                this.btCancel.Enabled = false;
            };

            client.DownloadDataCompleted += 
            (s, e) =>
            {
                DownloadBar.Value = 0;
                this.btBrowse.Enabled = true;
                this.btDownload.Enabled = true;
                this.btCancel.Enabled = false;
                this.Refresh();
            };

            client.DownloadProgressChanged +=
            (s, e) =>
            {
                DownloadBar.Value = e.ProgressPercentage;
                this.Refresh();
            };
        }
开发者ID:normanfernandez,项目名称:Downloader,代码行数:42,代码来源:Form1.cs

示例14: GetDocumentAsync

 public async Task<string> GetDocumentAsync(string address, CancellationToken cancel)
 {
     if (string.IsNullOrWhiteSpace(address))
     {
         throw new ArgumentNullException("address");
     }
     try
     {
         using (WebClient client = new WebClient())
         {
             using (CancellationTokenRegistration registration = cancel.Register(() => client.CancelAsync()))
             {
                 return await client.DownloadStringTaskAsync(address);
             }
         }
     }
     catch (Exception ex)
     {
         throw new IOException("Unable to get document from: " + address, ex);
     }
 }
开发者ID:richardschneider,项目名称:azure-activedirectory-identitymodel-extensions-for-dotnet,代码行数:21,代码来源:GenericDocumentRetriever.cs

示例15: WGet

 public static bool WGet(string URL, string destFileName)
 {
     DateTime EndTime = DateTime.Now.AddSeconds(30);
     try
     {
         WebClient Client = new WebClient();
         Client.DownloadFileAsync(new Uri(URL), destFileName);
         while ((Client.IsBusy) && (DateTime.Now < EndTime))
         {
             System.Threading.Thread.Sleep(200);
         }
         if (Client.IsBusy) Client.CancelAsync();
         Client.Dispose();
     }
     catch
     {
         if (File.Exists(destFileName)) File.Delete(destFileName);
         return false;
     }
     return true;
 }
开发者ID:hoeness2,项目名称:mcebuddy2,代码行数:21,代码来源:Internet.cs


注:本文中的System.Net.WebClient.CancelAsync方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。