Cannot implicitly convert type 'int' to '... Tasks <int>'
if it is asynchronous, it will return without errors, why it throws an error without async, async is useless 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; } Well, you can return the completed task:
return Task.FromResult(count); http://msdn.microsoft.com/en-us/library/hh194922.aspx
Why you want to return the task is a bit of a mystery. Conceptually, a task is a promise that something will happen in the future. In your case, this has already happened, so using the task is completely pointless.
As the error clearly states, you cannot return int as Task<int> . (unless you make an async method that does compile-time magic to create a Task<T> .
If your method is not asynchronous, you should not return Task<T> in the first place.
Instead, just return int directly.
If for some reason you need to return Task<T> , you can call Task.FromResult() to create a finished task with a given value.
There is nothing in this method indicating that it is an asynchronous method, except that you have told it that it returns a Task<int> .
However, you do not return Task<int> , you return count , int .
Since you are not waiting for the action to complete, I would remove the type of the returned Task<int> and replace it with just int , since this method is completely synchronous (except for the part that you do not expect anyway).
The code here is clearly incorrect. Try looking at the return type in your code. You are returned and int that do not match the return type expecting a Task<int> . If you are not going to use async in this method, you can simply change your return type to int .
However, if you insist on returning the Task<int> instead of int , you can use the following for the return statement
return Task.FromResult(count) This will translate the int to Task<int> . For more information on Task.FromResult you can visit: https://msdn.microsoft.com/en-us/library/hh194922(v=vs.110).aspx What is used for Task.FromResult <TResult> in C #