Lock variables in Script Task using C#

2019-03-05 11:24发布

问题:

I'm running a SQL Server Agent Job which has a script task with Microsoft Visual C# 2008 which is below:

public void Main()
{
        string filepath;
        filepath = Dts.Variables["User::FolderPath"].Value.ToString();
        Dts.Variables["User::FileExistsFlg"].Value = File.Exists(filepath);
        Dts.TaskResult = (int)ScriptResults.Success;
}

I get this error:

Executed as user: PSFACAMDWHSQL1\SYSTEM.
Microsoft (R) SQL Server Execute Package Utility
Version 10.50.4270.0 for 64-bit
Copyright (C) Microsoft Corporation 2010. All rights reserved.
Started: 18:06:19
Error: 2015-02-27 18:07:44.95
Code: 0xC001404F
Source: For Loop Container
Description: This Variables collection has already been unlocked. The Unlock method is called only once on a dispensed Variables collection. End Error

DTExec: The package execution returned DTSER_FAILURE (1).
Started: 18:06:19
Finished: 18:07:45
Elapsed: 85.613 seconds.
The package execution failed. The step failed.

I am not sure how to unlock the variable within the script task.

UPDATE: I have tried this method but I am missing something on the code:

  public void Main()
    {


        // Lock variables
        Dts.VariableDispenser.LockForRead("User::FolderPath");
        Dts.VariableDispenser.LockForWrite("User::FileExistsFlg");

        // Create a variables 'container' to store variables
        Variables vars = null;

        // Add variables from the VariableDispenser to the variables 'container'
        Dts.VariableDispenser.GetVariables(ref vars);

        string filepath;
        filepath = Dts.Variables["User::FolderPath"].Value.ToString();
        Dts.Variables["User::FileExistsFlg"].Value = File.Exists(filepath);

        // Release the locks
        vars.Unlock();

        Dts.TaskResult = (int)ScriptResults.Success;
    }
}

回答1:

Try converting your bool to an int.

Dts.Variables["User::FileExistsFlg"].Value = Convert.ToInt32(File.Exists(filepath));