private async Task GetImagesFiles(string radarImagesFolder)
{
DirectoryInfo lastRadarWrittenFolder = null;
var tt = new DirectoryInfo(textBoxRadarPath.Text).GetDirectories();
if (tt.Length > 0)
{
lastRadarWrittenFolder = new DirectoryInfo(textBoxRadarPath.Text).GetDirectories()
.OrderBy(d => d.CreationTimeUtc).First();
}
if (Directory.Exists(radarImagesFolder) && tt.Length > 0)
{
radarImages = Directory.GetFiles(lastRadarWrittenFolder.FullName, "*.png");
}
}
using it
private async void Completed(object sender, AsyncCompletedEventArgs e, Stopwatch sw, string urlAddress)
{
await GetImagesFiles(textBoxRadarPath.Text);
}
the problem is in the GetImagesFiles method on it's name GetImagesFiles there is a green line warning :
Severity Code Description Project File Line Suppression State Warning CS1998 This async method lacks 'await' operators and will run synchronously. Consider using the 'await' operator to await non-blocking API calls, or 'await Task.Run(...)' to do CPU-bound work on a background thread. Weather D:\Csharp Projects\Weather\Form1.cs 415 Active
i want to wait to get the files before continue the rest of the code. once radarImages array is not null and it's length is higher then 0 then continue the rest of the code.
CodePudding user response:
There is nothing async in GetImagesFiles
, so you can just remove async Task
from it. This alligns with suggestion from Task.Run
Etiquette Examples: Don't Use Task.Run
in the Implementation by Stephen Cleary. Also I would move setter out of the GetImagesFiles
with resulting code looking like:
private string[] GetImagesFiles(string radarImagesFolder)
{
DirectoryInfo lastRadarWrittenFolder = null;
var tt = new DirectoryInfo(textBoxRadarPath.Text).GetDirectories();
if (tt.Length > 0)
{
lastRadarWrittenFolder = new DirectoryInfo(textBoxRadarPath.Text).GetDirectories()
.OrderBy(d => d.CreationTimeUtc).First();
}
if (Directory.Exists(radarImagesFolder) && tt.Length > 0)
{
return Directory.GetFiles(lastRadarWrittenFolder.FullName, "*.png");
}
return null;
}
And invocation:
private async void Completed(object sender, AsyncCompletedEventArgs e, Stopwatch sw, string urlAddress)
{
var result = await Task.Run(GetImagesFiles(textBoxRadarPath.Text));
if(result != null)
{
radarImages = result;
}
}
P.S.
Though returning null
as marker can be a code smell but for brevity and due to lack of knowledge about language version you are using I've went with this approach.