Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create directory async (without using FileSystemWatcher)?

Tags:

c#

io

async-await

How can I make make the following code run asynchronously without having to create an extra thread on the thread pool (in other words without Task.Run(...))?

Directory.CreateDirectory("\\host\someNetworkDirectory");

Ideally, I would like to use it like this:

async SomeMethod(){
    //...
    await Directory.CreateDirectoryAsync("\\host\someNetworkDirectory");
    // stuff to do after ensuring the directory exists
    //...
}

I tried this answer (which suggest using FileSystemWatcher) but it does not work for folders.

like image 823
brakeroo Avatar asked Jan 18 '17 00:01

brakeroo


2 Answers

At the OS level, this function is strictly synchronous. WinAPI only has two functions for creating directories, CreateDirectory and CreateDirectoryEx. Neither of them accepts a callback.

Therefore, there is nothing you can do to avoid having to create a thread to make this asynchronous. Best you can hope for is to find a library which hides this away from you.

like image 136
Roman Starkov Avatar answered Sep 18 '22 05:09

Roman Starkov


Look at the static Task.Run methods.

async SomeMethod() {
    //...
    await Task.Run(() => Directory.CreateDirectory("\\host\someNetworkDirectory"));
    //...
}
like image 28
ILMTitan Avatar answered Sep 19 '22 05:09

ILMTitan