Cannot implicitly convert type 'int' to '…Tasks<int>'

亡梦爱人 提交于 2019-12-21 12:18:19

问题


if this is async, it'll return with no error, why is it throwing an error without being async, async is worthless in this operation.

public Task<int> countUp()
{
    string compare = txtTag.Text;
    int count = 0;
    for (int i = 0; i < dataGridView1.Rows.Count; i++)
    {
        if (compare == dataGridView1[0, i].Value.ToString())
        {
            BeginInvoke(new Action(() =>
            {
                count++;
                txtCount.Text = count.ToString();
            }));
        }
    }

    return count;
}

回答1:


Well, you could return a completed Task:

return Task.FromResult(count);

http://msdn.microsoft.com/en-us/library/hh194922.aspx

Why you'd want to return a Task is a bit of a mystery though. Conceptually, a Task represents a promise that something will happen at some time in the future. In your case, it's already happened, so using a Task is completely pointless.




回答2:


As the error clearly states, you can't return an int as a Task<int>. (unless you make it an async method, which does compile-time magic to create a Task<T>.

If your method isn't asynchronous, you shouldn't be returning a Task<T> in the first place.
Instead, just return int directly.

If, for some reason, you need to return a Task<T>, you can call Task.FromResult() to create a finished task with a given value.




回答3:


There is nothing in this method indicating that it is an asynchronous method, except for the fact that you've declared it to return Task<int>.

However, you're not returning a Task<int>, you're returning count, an int.

Since you're not waiting for the action to complete, I would remove the Task<int> return type and replace it with just int instead as this method is completely synchronous (except for the part you're not waiting for anyway).




回答4:


The code here is obviously incorrect. Try to look at the return type in your code. You are returning and int which mismatch the return type that expecting a Task<int>. If you are not going to use async await in this method, you can just change your return type to int.

However, if you insist on returning Task<int> instead of int, you can use the following for your return statement

return Task.FromResult(count)

This will wrap your int into Task<int>. For more information of Task.FromResult, you can visit : https://msdn.microsoft.com/en-us/library/hh194922(v=vs.110).aspx What is the use for Task.FromResult<TResult> in C#



来源:https://stackoverflow.com/questions/15462004/cannot-implicitly-convert-type-int-to-tasksint

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!