주어진 시나리오에서 비동기 성질 인 HttpWebRequest
/WebClient
을 사용할 수 있어야합니다.이 스레드는 단지 스레드가 아닌 완료 포트를 사용하여 이미 모든 것을 지원합니다.
"지금 죽이기"다시하십시오. 프로세스를 해체하지 않는 한 스레드를 중단해서는 안됩니다. 이것은 이며 나쁜 것이며 시스템을 손상된 상태 또는 복구 할 수없는 잠금 상태로 둘 수 있습니다. 그러나 도구 자체가 대안을 제공 할 수 있습니다 :
WebClient wc = new WebClient();
wc.DownloadFileCompleted += (sender, args) =>
{
if (args.Cancelled) Console.WriteLine("cancelled");
else if (args.Error != null) Console.WriteLine(args.Error.Message);
else Console.WriteLine("got it");
};
wc.DownloadFileAsync(uri, filePath);
// wc.CancelAsync(); // to abort
참고하는 비동기 콜백 (위의 DownloadFileCompleted
)은, 윈폼/WPF 같은 것을에서, UI 스레드로 전환해야 할 것입니다에; 예를 들면 다음과 같습니다.
wc.DownloadFileCompleted += (sender, args) =>
{
this.Invoke((MethodInvoker) delegate {
if (args.Cancelled) txtStatus.Text = "cancelled";
else if (args.Error != null) txtStatus.Text = args.Error.Message;
else txtStatus.Text = "got it";
});
};