我收到错误:
无法将类型'System.Data.DataTable'隐式转换为'System.Threading.Tasks.Task'
GetExternalMessage 正在执行Time,因此WinForm停止响应。 因此我想到了应用“任务等待”。但我仍然得到错误。我们如何在Task中返回dataTable?
以下是我正在尝试的代码:
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;
}
答案 0 :(得分:1)
正如错误所述,您无法隐式(或明确地)将DataTable
转换为Task<DataTable>
。
来自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.
因此,您应该从方法中返回DataTable
对象,如下所示:
async Task<DataTable> GetExtMsg(string dateFrom, string dateTo)
{
DL dl = new DL();
DataTable dt = new DataTable();
dt = dl.GetExternalMessage(dateFrom, dateTo);
return dt;
}
要使用此async
方法,您应该在方法名称前使用await
关键字,如下所示:
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);
}