gpt4 book ai didi

c# - 无法将 'DataTable' 隐式转换为 'Task'

转载 作者:太空宇宙 更新时间:2023-11-03 13:18:57 25 4
gpt4 key购买 nike

我收到错误:

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

GetExternalMessage 需要时间来执行,因此 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;

}

最佳答案

如错误所述,您不能隐式(或显式)转换 DataTableTask<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);
}

关于c# - 无法将 'DataTable' 隐式转换为 'Task<DataTable>',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25034896/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com