【问题标题】:Cannot implicitly convert 'DataTable' to 'Task<DataTable>'无法将“DataTable”隐式转换为“Task<DataTable>”
【发布时间】:2014-07-30 10:49:19
【问题描述】:

我收到错误:

无法将类型“System.Data.DataTable”隐式转换为“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;

}

【问题讨论】:

    标签: c# asynchronous async-await task


    【解决方案1】:

    正如错误所说,您不能隐式(或明确地)将DataTable 转换为Task&lt;DataTable&gt;

    来自MSDN

    You specify Task&lt;TResult&gt; 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);
    }
    

    【讨论】:

    • 如何在 Button1_Click() 中使用这个 GetExtMsg
    • 我已经更新了我的答案,但是我在答案中包含的 MSDN 链接中已经给出了async...await 的示例。
    • 我仍然无法获得响应式窗口。它只是在执行函数时挂起。
    • 1.如果没有看到涉及的其他代码,这是不可能回答的。 2. 这是一个单独的问题。请提出一个新问题并在必要时链接此问题。谢谢。
    猜你喜欢
    • 2019-08-30
    • 2015-10-20
    • 2011-11-29
    • 2016-05-14
    • 2014-07-22
    • 2017-01-20
    • 1970-01-01
    • 1970-01-01
    • 2012-10-04
    相关资源
    最近更新 更多