C# 中的 CreateDirectory() 是线程安全的吗? [英] Is CreateDirectory() in C# thread-safe?

查看:42
本文介绍了C# 中的 CreateDirectory() 是线程安全的吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我能否安全地尝试从两个不同的线程创建 相同 目录,而不会让其中之一引发异常或遇到其他问题?

Can I safely attempt to create the same directory from two different threads, without having one of them throw an exception, or run into other issues?

请注意,根据 MSDN,可以在已经存在的目录上调用 CreateDirectory() ,在这种情况下,该方法预计什么都不做.

Note that according to MSDN, it is OK to call CreateDirectory() on a directory which already exists, in which case the method is expected to do nothing.

推荐答案

Directory.CreateDirectory 调用本身在多线程中是安全的.如果您这样做,它不会破坏程序或文件系统状态.

The Directory.CreateDirectory call itself is safe to make from multiple threads. It will not corrupt program or file system state if you do so.

然而,不可能以这种方式调用 Directory.CreateDirectory 来保证它不会抛出异常.文件系统是一个不可预测的野兽,它可以在任何给定时间被您控制之外的其他程序更改.例如,很可能会出现以下情况

However it's not possible to call Directory.CreateDirectory in such a way to guarantee it won't throw an exception. The file system is an unpredictable beast which can be changed by other programs outside your control at any given time. It's very possible for example to see the following occur

  • 程序 1 线程 1:为 c:\temp\foo 调用 CreateDirectory 并成功
  • 程序 2 线程 1:删除程序 1 用户对 c:\temp 的访问权限
  • 程序 1 线程 2:调用 CreateDirectory 并由于访问权限不足而抛出
  • Program 1 Thread 1: Call CreateDirectory for c:\temp\foo and it succeeds
  • Program 2 Thread 1: Removes access to c:\temp from program 1 user
  • Program 1 Thread 2: Call CreateDirectory and throws due to insufficient access

简而言之,您必须假设 Directory.CreateDirectory,或者实际上任何接触文件系统的函数,都可以并且将会相应地抛出和处理.

In short you must assume that Directory.CreateDirectory, or really any function which touches the file system, can and will throw and handle accordingly.

这篇关于C# 中的 CreateDirectory() 是线程安全的吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆