【问题标题】:Cannot implicitly convert type 'string' to 'System.Threading.Tasks.Task<string>' in c#无法在 c# 中将类型“string”隐式转换为“System.Threading.Tasks.Task<string>”
【发布时间】:2021-12-25 04:42:09
【问题描述】:

我有这个代码

    private void button1_Click(object sender, EventArgs e)
    {
        //===========> Getting error here <==================//
        textBox2.Text = CallFunc(textBox1.Text);
    }

    static async Task<string> CallFunc(string str)
    {
        Program p = new Program();
        string s = await p.DocumentToText(str);
        return s;
    }


public async Task<string> DocumentToText(string path)
    {
        string txt = String.Empty;
        AmazonTextractClient client = new AmazonTextractClient(key, Skey, reg);
        //some AWS functionality

        Thread.Sleep(2000);
        txt = "hello world";
        return txt;
     }

我把这个button1_Click函数改成了

    private void button1_Click(object sender, EventArgs e)
    {
        var d = await CallFunc(textBox1.Text);
        textBox2.Text = d.Results();
    }

正如这个问题的一个答案所建议的那样

Cannot implicitly convert type 'string' to 'System.Threading.Tasks.Task<string>'

但是还是不行

【问题讨论】:

  • 不要在异步方法中使用 Thread.Sleep。请改用 await Task.Delay。

标签: c# asynchronous async-await


【解决方案1】:

button1_Click 事件中添加async

private async void button1_Click(object sender, EventArgs e)
{
    var d = await CallFunc(textBox1.Text);
    textBox2.Text = d;
}

【讨论】:

  • 错误:字符串不包含来自“结果”的定义
  • 使用 textBox2.Text = d;
【解决方案2】:

在 button1_Click 方法中使用异步任务

private async Task button1_Click(object sender, EventArgs e)
{
    var d = await CallFunc(textBox1.Text);
    textBox2.Text = d.Results();
}

【讨论】:

    猜你喜欢
    • 2013-01-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-27
    相关资源
    最近更新 更多