WebClient.CancelAsync() and TargetInvocationException

D

deerchao

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#11974fe21507faae) 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();
}
}
 
D

deerchao

I don't know what's better than Application.ThreadException event to
catch this exception. But it works strangely: if in the event I pop a
MessageBox, the application continues to run, If I don't, it will quit
immediately! I believe it should be my decision to make whether or not
exit the application, but not Application or whatever.
What's wrong with my code?

static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);

Application.ThreadException +=
Application_ThreadException;
Application.Run(new MainForm());
}

static void Application_ThreadException(object sender,
ThreadExceptionEventArgs e)
{
//logger.Error(e.Exception.Message);
//if the statement below is not present, application will
exit at once!
//but if it's here, application continues to run.
MessageBox.Show(e.Exception.Message);
}
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top