NoughT
NoughT

Reputation: 673

Allocate separate thread per event in FileSystemWatcher

I am developing a windows service that contains the FileSystemWatcher. Once file creates, I have to make some network calls to a web API.

Please look at below code lines.

watcher.Created += new FileSystemEventHandler((object source, FileSystemEventArgs e) => { ProcessCreateEvent(e); });

Event handler

private async void ProcessCreateEvent(FileSystemEventArgs e){
      // make some network calls and do certain tasks
      // network calls doing asynchronously
}

I did in deep about the FileSystemWatcher and I understand that it is not the good practice to handle the network call in ProcessCreateEvent method. So how can I allocate the separate thread for each file change?

Upvotes: 0

Views: 1591

Answers (2)

satnhak
satnhak

Reputation: 9861

Events already support async, so you can just do something like:

watcher.Created += this.ProcessCreateEvent;

private async void ProcessCreateEvent(object sender, FileSystemEventArgs e)
{
    var result = await asyncApi.GetStuffAsync();
}

You don't need to spin up another Task unless the non-async stuff you are doing in the event handler is expensive.

Upvotes: 3

Bob Dust
Bob Dust

Reputation: 2460

I think it can simply be done by making ProcessCreateEvent asynchronous like this:

    private async Task ProcessCreateEvent(FileSystemEventArgs e)
    {
        // make some network calls and do certain tasks
        // network calls doing asynchronously
        await Task.Run(async () => {
            var client = new HttpClient();
            var response = await client.GetAsync("http://localhost:54522/api/values");
            var result = await response.Content.ReadAsStringAsync();
        });
    }

Upvotes: 0

Related Questions