You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Azure Functions中Directory.Exists()竟清空Static Dictionary?求解释

问题:静态Dictionary在调用Directory.CreateDirectory后被清空

我遇到了一个无法理解的奇怪交互现象:静态Dictionary会在端点函数执行结束后被清空,而且这种情况只在调用Directory静态类方法时才会出现。

本文目的是确认他人是否能复现该问题,并寻求此行为的合理解释。

环境配置

本地Azure Functions项目,包含两个端点:/start和/stop,同时有一个包含静态字典的类:

public class State{
    public static Dictionary<string,string> TestValues = new Dictionary<string, string>();
}

通过/start端点向Dictionary中添加值,再通过/stop端点访问并返回该值。

正常流程

/start端点代码如下:

public static async Task<IActionResult> startTraining(
    [HttpTrigger(AuthorizationLevel.Function, "post", Route = "training/{trainingId}/start")] HttpRequest req,
    string trainingId,
    ILogger log)
{  
    string newFolderPath = Environment.CurrentDirectory + $"/Training-{trainingId}";

    State.TestValues.Add("MyKey", "MyValue");
    return new OkObjectResult("Added a word");
    if (!Directory.Exists(newFolderPath))
    {
        Directory.CreateDirectory(newFolderPath);
    }
}

此时调用/stop端点(代码如下):

public static async Task<IActionResult> stopTraining(
    [HttpTrigger(AuthorizationLevel.Function, "post", Route = "training/{trainingId}/stop")] HttpRequest req,
    string trainingId,
    ILogger log)
{
    return new OkObjectResult(State.TestValues["MyKey"]);
}

会正确返回MyValue,因为代码从未执行到Directory.Exists()。

异常行为

如果调整代码顺序,先执行Directory.Exists(),再向Dictionary中添加值:

public static async Task<IActionResult> startTraining(
    [HttpTrigger(AuthorizationLevel.Function, "post", Route = "training/{trainingId}/start")] HttpRequest req,
    string trainingId,
    ILogger log)
{  
    string newFolderPath = Environment.CurrentDirectory + $"/Training-{trainingId}";

    if (!Directory.Exists(newFolderPath))
    {
        Directory.CreateDirectory(newFolderPath);
    }
    State.TestValues.Add("MyKey", "MyValue");
    return new OkObjectResult("Added a word");
}

此时调用/stop端点会返回错误:

System.Private.CoreLib: The given key 'MyKey' was not present in the dictionary.

我完全无法理解Directory方法为何会影响Dictionary,二者唯一的共同点就是都是静态的。

编辑内容

后续发现问题仅在使用Directory.CreateDirectory在bin/output/目录下创建文件夹时出现,在其他位置创建则不会清空Dictionary中的项,但仍不清楚背后的原因。

内容的提问来源于stack exchange,提问作者StupidUser3186

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.16 21:31:11