简体   繁体   English

无法将类型“字符串”隐式转换为“System.Threading.Tasks.Task”<string> &#39;

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

I am new to asynchronous programming, so after going through some async sample codes, I thought of writing a simple async code我是异步编程的新手,所以在浏览了一些异步示例代码之后,我想到了编写一个简单的异步代码

I created a simple Winform application and inside the Form I wrote the following code.我创建了一个简单的 Winform 应用程序,并在表单中编写了以下代码。 But its just not working但它只是不工作

private Task<string> methodAsync() {
    Thread.Sleep(10000);
    return "Hello"; //Error: Cannot implicitly convert type 'string' to 'System.Threading.Tasks.Task<string>'
}

private async void button1_Click(object sender, EventArgs e)
{
    string s = await methodAsync();
    MessageBox.Show(s);
}

Could someone please put some light here..有人可以在这里放一些灯吗..

The listed return type of the method is Task<string> .列出的方法的返回类型是Task<string> You're trying to return a string .您正在尝试返回一个string They are not the same, nor is there an implicit conversion from string to Task<string> , hence the error.它们不相同,也没有从 string 到Task<string>的隐式转换,因此出现错误。

You're likely confusing this with an async method in which the return value is automatically wrapped in a Task by the compiler.您可能会将其与async方法混淆,在async方法中,编译器会自动将返回值包装在Task Currently that method is not an async method.目前该方法不是异步方法。 You almost certainly meant to do this:您几乎肯定打算这样做:

private async Task<string> methodAsync() 
{
    await Task.Delay(10000);
    return "Hello";
}

There are two key changes.有两个关键变化。 First, the method is marked as async , which means the return type is wrapped in a Task , making the method compile.首先,该方法被标记为async ,这意味着返回类型被包装在一个Task ,使该方法可以编译。 Next, we don't want to do a blocking wait.接下来,我们不想进行阻塞等待。 As a general rule, when using the await model always avoid blocking waits when you can.作为一般规则,使用await模型时总是await避免阻塞等待。 Task.Delay is a task that will be completed after the specified number of milliseconds. Task.Delay是在指定的毫秒数后完成的任务。 By await -ing that task we are effectively performing a non-blocking wait for that time (in actuality the remainder of the method is a continuation of that task).通过await执行该任务,我们有效地执行了该时间的非阻塞等待(实际上,该方法的其余部分是该任务的延续)。

If you prefer a 4.0 way of doing it, without using await , you can do this:如果您更喜欢 4.0 的方式,而不使用await ,您可以这样做:

private Task<string> methodAsync() 
{
    return Task.Delay(10000)
        .ContinueWith(t => "Hello");
}

The first version will compile down to something that is more or less like this, but it will have some extra boilerplate code in their for supporting error handling and other functionality of await we aren't leveraging here.第一个版本将编译成或多或少这样的东西,但它会有一些额外的样板代码,用于支持错误处理和其他我们没有利用的await功能。

If your Thread.Sleep(10000) is really meant to just be a placeholder for some long running method, as opposed to just a way of waiting for a while, then you'll need to ensure that the work is done in another thread, instead of the current context.如果你的Thread.Sleep(10000)真的只是作为一些长时间运行方法的占位符,而不是等待一段时间的方式,那么你需要确保工作在另一个线程中完成,而不是当前的上下文。 The easiest way of doing that is through Task.Run :最简单的方法是通过Task.Run

private Task<string> methodAsync() 
{
    return Task.Run(()=>
        {
            SomeLongRunningMethod();
            return "Hello";
        });
}

Or more likely:或者更有可能:

private Task<string> methodAsync() 
{
    return Task.Run(()=>
        {
            return SomeLongRunningMethodThatReturnsAString();
        });
}

Use FromResult Method使用 FromResult 方法

public async Task<string> GetString()
{
   System.Threading.Thread.Sleep(5000);
   return await Task.FromResult("Hello");
}

Beyond the problematic use of async as pointed out by @Servy, the other issue is that you need to explicitly get T from Task<T> by calling Task.Result.除了@Servy 指出的async使用有问题之外,另一个问题是您需要通过调用 Task.Result 从Task<T>显式获取T Note that the Result property will block async code, and should be used carefully.请注意,Result 属性将阻止异步代码,应谨慎使用。

Try:尝试:

private async void button1_Click(object sender, EventArgs e)
{
    var s = await methodAsync();
    MessageBox.Show(s.Result);
}

In my case.就我而言。

        string ip = _GetStoreIpaddress().Result;


    private async Task<string> _GetStoreIpaddress()
    {
        string _store_iP = "";
        var Ip_address = await App.SQLiteDb.GetItemsAsync();
        if (Ip_address != null)
        {
            _store_iP = Ip_address.ToString();
        }

        return _store_iP;
    }
    //source    
    public async Task<string> methodName()
            {
             return Data;
             }

    //Consumption
     methodName().Result;

Hope this helps :)希望这可以帮助 :)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 无法隐式转换类型&#39;System.Threading.Tasks.Task <String> “串” - Cannot implicitly convert type 'System.Threading.Tasks.Task<String> to 'string' 错误 CS0029:无法将类型“字符串”隐式转换为“System.Threading.Tasks.Task”<string> '</string> - Error CS0029: Cannot implicitly convert type 'string' to 'System.Threading.Tasks.Task<string>' 无法将类型“字符串”隐式转换为“System.Threading.Tasks.Task”<string> ' 在 c#</string> - Cannot implicitly convert type 'string' to 'System.Threading.Tasks.Task<string>' in c# 无法隐式转换类型&#39;System.Threading.Tasks.Task <object> 在SignalR中从&#39;到&#39;string&#39; - Cannot implicitly convert type 'System.Threading.Tasks.Task<object>' to 'string' in SignalR 无法将类型&#39;void&#39;隐式转换为&#39;System.Threading.Tasks.Task&#39; - Cannot implicitly convert type 'void' to 'System.Threading.Tasks.Task' 无法隐式转换类型&#39;System.Threading.Tasks.Task - Cannot implicitly convert type 'System.Threading.Tasks.Task 无法将类型&#39;bool&#39;隐式转换为&#39;System.Threading.Tasks.Task&#39; - Cannot implicitly convert type 'bool' to 'System.Threading.Tasks.Task' 无法将类型&#39;System.Collections.Generic.List &lt;&gt;&#39;隐式转换为&#39;System.Threading.Tasks.Task &lt;&gt;&gt; - Cannot implicitly convert type 'System.Collections.Generic.List<>' to 'System.Threading.Tasks.Task<>> 无法将类型&#39;bool&#39;隐式转换为&#39;system.threading.tasks.task bool&#39; - Cannot implicitly convert type 'bool' to 'system.threading.tasks.task bool' 无法将类型“System.Threading.Tasks.Task”隐式转换为“Windows.Foundation.IAsyncAction”。 存在显式转换 - Cannot implicitly convert type 'System.Threading.Tasks.Task' to 'Windows.Foundation.IAsyncAction'. An explicit conversion exists
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM