我有一个数据似乎被重置为其默认值的问题。类如下(objectIDs是一个简单的枚举):
public class Output_args: EventArgs {
public objectIDs outputtype;
public int internalID;
public int verdict;
public int outputID;
public long entrytime;
public Output_args Copy() {
Output_args args = new Output_args();
args.entrytime = this.entrytime;
args.internalID = this.internalID;
args.outputID = this.outputID;
args.outputtype = this.outputtype;
args.verdict = this.verdict;
return args;
}
}
以下代码创建对象。它在一个特定的线程中运行,比如说 Thread1。
class Class1 {
EventWaitHandle ewh = new EventWaitHandle(false, EventResetMode.AutoReset);
public event EventHandler<Output_args> newOutput;
public void readInput(){
List<Output_args> newoutputlist = new List<Output_args>();
/*
* code to determine the outputs
*/
Output_args args = new Output_args();
args.outputtype = objectIDs.stepID;
args.internalID = step[s].ID;
args.verdict = verdict;
args.entrytime = System.DateTime.Now.Ticks;
newoutputlist.Add(args.Copy());
if (newOutput != null && newoutputlist.Count > 0) {
// several outputs are being sent sequentially but for simplicity i've removed the for-loop and decision tree
try {
newOutput(null, newoutputlist[0].Copy());
} catch (Exception) { }
}
}
}
此事件的订阅者中有 1 个具有以下代码。处理器方法在 camerafeed 的线程上运行。newOutput 事件处理程序正在 Thread1 上运行。
class Class2: Form {
private Output_args lastoutput = new Output_args();
public void newOutput(object sender, Output_args args) {
lock (lastoutput) {
lastoutput = args.Copy();
}
}
public void processor(){
lock (lastoutput) {
if (lastoutput.entrytime + 10000000 > System.DateTime.Now.Ticks) {
// do something
}
}
}
}
当调用 Class2 的事件处理程序“newOutput”时,调试器显示副本按预期工作,并且“entrytime”被赋予预期的滴答数。
但是,当处理器方法想要读取“入口时间”时,它的值为 0。所有其他字段也分配了它们的默认值。
我尝试用 long 类型的简单字段替换对象“lastoutput”并删除了锁,但结果是相同的:它在“newOutput”中正确分配,但在处理器方法中具有默认值(0)。
关于为什么会发生这种情况的任何想法?