I am trying to implement asynchronous programming into my windows forms app, and am receiving this error message when trying to return the task. I do not know how to convert an 'int' to a 'System.Func'.
I am returning an int instead of a bool because when i try to return the bool, I get an error stating asynchronous methods have to return an int or a task.
private async void Button1_Click(object sender, EventArgs e)
{
Task<int> task = new Task<int>(CheckForFiles());
task.Start();
label1.Text = "Checking for file...";
int FilesPresent = await task;
if (FilesPresent == 1)
{
label1.Text = "file present";
}
else
{
label1.Text = "file missing";
}
}
private int CheckForFiles()
{
int fileExists = 0;
bool result = File.Exists(@"FileLocation");
if (result == true)
{
fileExists = 1;
}
else
{
fileExists = 0;
}
return (fileExists);
}
I expect to be able to update this method to allow for asynchronous programming to function successfully
First off let me say: you are doing this fundamentally wrong. You do NOT want to make a new thread to do an IO task, which is what you are trying to do. But that's not the problem that is blocking you right now.
The problem with your code that you've made the common error of confusing CheckForFiles -- which is a function that returns an integer with CheckForFiles() which is an execution of the function, and therefore, an integer.
You do NOT want this:
Task<int> task = new Task<int>(CheckForFiles());
That is the same as
int result = CheckForFiles();
Task<int> task = new Task<int>(result);
which is plainly nonsense. What you want is:
Task<int> task = new Task<int>(CheckForFiles);
That is do not call the function; make a task from the function.
Or use a lambda if the code is more complex:
Task<int> task = new Task<int>(() => CheckForFiles());
Or if you need multiple statements:
Task<int> task = new Task<int>(() => { return CheckForFiles(); } );
I am returning an int instead of a bool because when i try to return the bool, I get an error stating asynchronous methods have to return an int or a task.
Then you are doing something else wrong too. You should be able to make CheckForFiles return bool and use a Task<bool>.
But once again do not make a new thread to do an IO task. That works against the whole idea of asynchrony in windows forms, which is that we want to keep the IO tasks asynchronous on the UI thread. Re-think how you are adding asynchrony to your program.
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