Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

task

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;
}
like image 436
ploxtic Avatar asked Mar 17 '13 14:03

ploxtic


3 Answers

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.

like image 164
spender Avatar answered Oct 16 '22 10:10

spender


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.

like image 10
SLaks Avatar answered Oct 16 '22 08:10

SLaks


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#

like image 4
jet_choong Avatar answered Oct 16 '22 10:10

jet_choong