3

I am getting Error:

Cannot implicitly convert type 'System.Data.DataTable' to 'System.Threading.Tasks.Task'

The GetExternalMessage is taking Time to execute and hence the WinForm Stops responsing. Hence I thought of appling "Task Await". But still i am getting error. How can we return a dataTable in Task?

Below is the code I am trying:

private void button1_Click(object sender, EventArgs e)
{
    dtFrom.Format = DateTimePickerFormat.Short;
    dtTo.Format = DateTimePickerFormat.Short;
    DataTable dt = new DataTable();
    //dt =  GetExtMsg(dtFrom.Text, dtTo.Text);

}

async Task<DataTable> GetExtMsg(string dateFrom, string dateTo)
{
    DL dl = new DL();
    DataTable dt = new DataTable();
    dt =  dl.GetExternalMessage(dateFrom, dateTo);
    Task<DataTable> tastDT = dt;

}
Jaskier
  • 1,075
  • 1
  • 10
  • 33
Prateik
  • 241
  • 2
  • 6
  • 14

1 Answers1

3

As the error says, you cannot implicitly (or explicitly for that matter) convert a DataTable to a Task<DataTable>.

From MSDN:

You specify Task<TResult> as the return type of an async method if the return statement of the method specifies an operand of type TResult.

Therefore you should just return the DataTable object from your method like so:

async Task<DataTable> GetExtMsg(string dateFrom, string dateTo)
{
 DL dl = new DL();
 DataTable dt = new DataTable();
 dt =  dl.GetExternalMessage(dateFrom, dateTo);
 return dt;
}

To consume this async method, you should use the await keyword before the method name, like so:

private async void button1_Click(object sender, EventArgs e)
{
 dtFrom.Format = DateTimePickerFormat.Short;
 dtTo.Format = DateTimePickerFormat.Short;
 DataTable dt = new DataTable();
 dt = await GetExtMsg(dtFrom.Text, dtTo.Text);
}
shree.pat18
  • 21,449
  • 3
  • 43
  • 63
  • How can I use this **GetExtMsg** in Button1_Click()? – Prateik Jul 30 '14 at 11:33
  • I have updated my answer, but a sample of `async...await` is already given in the MSDN link that I have included in answer. – shree.pat18 Jul 30 '14 at 11:37
  • I am Still Not able to get the responsive Window. It just hangs when executing the function. – Prateik Jul 30 '14 at 12:48
  • 1
    1. That is impossible to answer without seeing other code involved. 2. That is a separate question. Please ask a new question and link this one if necessary. Thanks. – shree.pat18 Jul 30 '14 at 12:50