为什么在多线程中Marshal.PtrToStructure有时候取出来的Struct的某些字段值为null,高手有解决方法吗?

poorhouse 2006-12-28 11:14:45
1、定义一个结构
struct TestStruct
{
public Intptr next;
public string strUsername;
public string strAddress;
...
}

2、将TestStruct的实例做为循环链表的节点
Intptr ptrLastNode = Intptr.Zero;
Intptr ptrTemp = Intptr.Zero;
for(int i=0;i<100;i++)
{
TestStruct test = new TestStruct();
test.next = ptrTemp;
test.strUsername = "Name" + i;
test.strAddress = "Addr" + i;
while(true)
{
try
{
ptrTemp = Marshal.AllocHGlobal(Marshal.Sizeof(TestStruct));
Marshal.StructureToPtr(test, ptrTemp, true);
if(i.Equals(0))
{
ptrLastNode = ptrTemp;
}
break;
}
catch(Execption ep)
{
MessageBox.Show(ep.Message);
}
}
}
try
{
TestStruct lastNodeStruct = (TestStruct)Marshal.PtrToStructure(ptrLastNode ,typeof(TestStruct ));
lastNodeStruct.next = ptrTemp;
Marshal.StructureToPtr(lastNodeStruct,ptrLastNode,true);
}
catch(Execption ep)
{
MessageBox.Show(ep.Message);
}

3、在其它线程中(可能有多个线程在操作链表)使用Marshal.PtrToStructure得到的结构中的字段值有时候为null,请问是什么原因导致?
...全文
201 1 打赏 收藏 转发到动态 举报
写回复
用AI写文章
1 条回复
切换为时间正序
请发表友善的回复…
发表回复
真相重于对错 2006-12-29
  • 打赏
  • 举报
回复
因为.net 有垃圾回收装置也就是说他的地址内容可能是不定的,Marshal.PtrToStructure 把它写入非托管内存。它的指针域,可能是错误的。
你做链表,直接用引用即可,没必要用intptr


110,526

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 C#
社区管理员
  • C#
  • Web++
  • by_封爱
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

让您成为最强悍的C#开发者

试试用AI创作助手写篇文章吧