Allow event handler of FileSystemWatcher to be Task

For FileSystemWatcher event handlers Created, Changed, Deleted etc. I need the function to return a Task since my ReadCSV() returns async Task and performs database operations, but that throws the error,

Task OnChanged has the wrong return type

If I leave OnChanged() to async void then I get the error:

Cannot access a disposed object

When I try and do a database operation.

protected override async Task ExecuteAsync(CancellationToken stoppingToken)
    FileSystemWatcher watcher = new FileSystemWatcher("/app/Import");

    watcher.NotifyFilter = NotifyFilters.Attributes
                         | NotifyFilters.CreationTime
                         | NotifyFilters.DirectoryName
                         | NotifyFilters.FileName
                         | NotifyFilters.LastAccess
                         | NotifyFilters.LastWrite
                         | NotifyFilters.Security
                         | NotifyFilters.Size;

    watcher.Filter = "*.csv";
    watcher.Created += OnChanged;
    watcher.EnableRaisingEvents = true;

    while (!stoppingToken.IsCancellationRequested)
        await Task.Delay(5000);

private async Task OnChanged(object sender, FileSystemEventArgs args)
    if(args.ChangeType == WatcherChangeTypes.Created)
       await _run.ReadCSV();

Read more here:

Content Attribution

This content was originally published by DevEng at Recent Questions - Stack Overflow, and is syndicated here via their RSS feed. You can read the original post over there.

%d bloggers like this: