我正在编写一个与第 3 方程序交互的程序。这个第 3 方程序允许用户制作可以运行在第 3 方程序中进行的步骤记录的按钮。但!这些按钮还可以运行用户定义的批处理文件。因此,我使用此功能通过创建文件并检查这些文件是否存在来与我的程序进行交互。
我的程序由两个类组成,一个 Actionlistener 和一个 Actionperformer。actionperformer 包含一个带有可能操作的枚举。
读取函数如下所示:
static public void CheckForActions()
{
//For every action in the Enum
foreach (ActionPerformer.PossibleActions action in Enum.GetValues(typeof(ActionPerformer.PossibleActions)))
{
//If a file exists with the same name as the current action
if (File.Exists(_location + action.ToString()))
{
//Delete "message" and create a new thread to perform this action.
File.Delete(_location + action);
Thread _t = new Thread(() =>
{
new ActionPerformer(action);
});
_t.SetApartmentState(ApartmentState.STA);
_t.Start();
//Add thread to list so they can be joined propperly
_list.Add(_t);
//Write information to log
Logger.LogInfo(_t, "Starting new action: " + action.ToString(), DateTime.Now);
}
}
//If there are items in the list
if (_list.Count > 0)
{
//Dispose every thread once its done.
foreach (Thread _t in _list)
{
_t.Join();
Logger.LogInfo("Finishing action.", DateTime.Now);
}
_list.Clear();
}
}
ActionPerformer 类看起来像这样:
class ActionPerformer
{
public enum PossibleActions
{
action1,
action2,
}
public ActionPerformer(PossibleActions action)
{
Logger.LogInfo(action.ToString(), DateTime.Now);
}
}
因此,当我以 action1 作为参数运行程序并读取记录器输出时,我应该得到如下信息:
Starting new action: action1 [13:30:05]
action1 [13:30:05]
Finishing action. [13:30:05]
但是第一次调用 CheckForActions 时,我总是将其作为输出:
Starting new action: action1 [13:30:05]
action2 [13:30:05] //Notice how it is not action1?
Finishing action. [13:30:05]
我第二次调用 CheckForActions,一切都按预期工作......
有谁知道发生了什么?