I'm developing a Windows Forms application with C#, .NET Framework 4.0 and Visual Studio 2012 Premium.
I have this method:
private void firstPhaseBtn_Click(object sender, EventArgs e)
{
var task = Task.Factory.StartNew(() =>
{
if (_viewModel == null)
_viewModel = new MainViewModel();
this.BeginInvoke((Action)delegate()
{
labelLoading.Text = "Creando orden...";
labelLoading.Visible = true;
Models.FirstPhaseModel model = new Models.FirstPhaseModel()
{
// Set data.
};
orderNumberLabel.Text = _viewModel.FirstPhase(model);
firstPhaseBtn.Enabled = true;
labelLoading.Text = string.Empty;
labelLoading.Visible = false;
});
});
try
{
task.Wait();
}
catch (Exception)
{
MessageBox.Show(this, _viewModel.ClientCustomError, "Error");
}
}
On _viewModel.FirstPhase(model);
I do a HTTP Get Request to a web service.
My problem here is the try catch
block doesn't work. I always get an unhandled exception.
I have tried to run the project in Debug, Release, and running the executable file on Release folder, but I always get an unhandled exception.
I have also tried to put the try catch
block inside the task, but with the same result.
How can I handled an exception in a Task?
I have also tried add this:
.ContinueWith(t =>
{
labelLoading.Visible = false;
labelLoading.Text = string.Empty;
MessageBox.Show(this, _viewModel.ClientCustomError, "Error");
}, TaskContinuationOptions.OnlyOnFaulted);
But I'm still getting a System.Reflection.TargetInvocationException.