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;
}
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.
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.
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#
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With