I found a thread (http://groups.google.com/group/
microsoft.public.dotnet.languages.csharp/browse_thread/thread/
b154f44522b5e083/11974fe21507faae?
lnk=gst&q=webclient.CancelAsync&rnum=1#11974fe2150 7faae) about this
issue, but it can't solve my problem.
I simply put a progressbar (to show the progress of the downloading),
a lable (to show what's downloading), and a button (to cancel the
download) on a form. If I click cancel button while downloading, there
comes a TargetInvocationException. How should I avoid it, or at least
catch it?
And here is the code:
DownloadProgressForm f=new DownloadProgressForm(url, message)
if(f.ShowDialgo()==DialogResult.OK)
{
...
}
public partial class DownloadProgressForm : Form
{
private readonly string url;
private byte[] data;
private WebClient client;
public DownloadProgressForm(string url, string message)
{
InitializeComponent();
lblStatus.Text = message;
this.url = url;
}
public byte[] Data
{
get { return data; }
}
private void DownloadProgressForm_Load(object sender,
EventArgs e)
{
client = new WebClient();
client.DownloadProgressChanged += DownloadProgressChanged;
client.DownloadDataCompleted += DownloadDataCompleted;
client.DownloadDataAsync(new Uri(url));
}
void DownloadDataCompleted(object sender,
DownloadDataCompletedEventArgs e)
{
if (e.Cancelled)
{
DialogResult =
System.Windows.Forms.DialogResult.Cancel;
}
else
{
DialogResult = System.Windows.Forms.DialogResult.OK;
}
data = e.Result;
Close();
}
void DownloadProgressChanged(object sender,
DownloadProgressChangedEventArgs e)
{
progressBar1.Value = (int)(e.BytesReceived * 100 /
e.TotalBytesToReceive);
}
private void btnCancel_Click(object sender, EventArgs e)
{
client.CancelAsync();
}
}