0

I am developing a windows form application. Following is the code segment that is executed on a button click event.

var taskExecute= Task<Datatable>.Run(() =>
{
    return = GetDt(); // time consuming method 
})

.ContinueWith(task=>
{
   this.datagridVal.Datasource = task.Result;
}, TaskScheduler.FromCurrentSynchronizationContext());

this works fine. But If I start the thread and then immediately click on the cross(x) button of the form then the following line of code throws NullReferenceException (most probably because the form has been already disposed and so is the datagrid control)

this.datagridVal.Datasource = task.Result;

How can I modify the code so that this block of code does not throw any exception if the form is closed when the thread is running? Also please suggest if there is any better way to handle the scenario using

Anirban Paul
  • 1,065
  • 1
  • 16
  • 22
  • possible duplicate of [How can SynchronizationContext.Current of the main thread become null in a Windows Forms application?](http://stackoverflow.com/questions/4659257/how-can-synchronizationcontext-current-of-the-main-thread-become-null-in-a-windo) – Adi Lester Feb 24 '14 at 16:45
  • Hmm, NRE is quite odd, this should generate an ObjectDisposedException. Might be a DGV quirk. Either way, checking for datagridVal.IsDisposed ought to be a workaround. Really rather best to interlock the closing of the form with the completion of any pending task. – Hans Passant Feb 24 '14 at 17:49
  • GetDt() is executing a query to fetch large chunk of data in form of datatable. What I want is to cancel the thread as soon as close button is clicked. But since there is no loop in GetDt(), I am not sure whether I can have a proper way to cancel the thread when Close button is clicked. And in that form more than one thred of similar type(DB data fetch) can be running when The close button is clicked. I want to cancel all the threads when Close button is clicked. – Anirban Paul Feb 25 '14 at 02:11

1 Answers1

0

If the problem indeed comes from the fact that the form is disposed, then you could handle that with this.IsDisposed:

var taskExecute= Task<Datatable>.Run(() =>
{
    return = GetDt(); // time consuming method 
})

.ContinueWith(task=>
{
    if (!this.IsDisposed)
    {
        this.datagridVal.Datasource = task.Result;
    }
}, TaskScheduler.FromCurrentSynchronizationContext());
Pedro Pombeiro
  • 1,654
  • 13
  • 14