修改列表(结构)中的项目属性
在(结构)列表中,我经常必须使用此代码修改项目的属性,
Private Sub ChangeState(ByVal ww As WebWorker, _
ByVal NewState As WorkerState)
Dim oWBB As WebWorker = ListWebWorkers.Find(Function(item As WebWorker) item.Browser.Name.ToLower = ww.Browser.Name.ToLower)
If oWBB.Browser IsNot Nothing Then
ListWebWorkers.Remove(oWBB)
oWBB = ww
oWBB.State = NewState
ListWebWorkers.Add(oWBB)
End If
End Sub
但是当两个或多个项目调用此子过程时,这会出现问题。其中一项可能已被删除。这段代码是在ui线程中执行的,并且必须如此
,那么有没有更好的方法来修改列表结构中的项目?
谢谢
In a list(of structure), i constantly have to modifiy the property of items using this code
Private Sub ChangeState(ByVal ww As WebWorker, _
ByVal NewState As WorkerState)
Dim oWBB As WebWorker = ListWebWorkers.Find(Function(item As WebWorker) item.Browser.Name.ToLower = ww.Browser.Name.ToLower)
If oWBB.Browser IsNot Nothing Then
ListWebWorkers.Remove(oWBB)
oWBB = ww
oWBB.State = NewState
ListWebWorkers.Add(oWBB)
End If
End Sub
But this give problem when two or more of the items call this sub procedure. in that one item may already have been removed. This code is executed in the ui thread, and has to be
so is there a better way to modify the items in list structure?
thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
在您当前的代码中,您没有检查正确的项目是否存在(您正在检查
oWBB.Browser
,但您应该检查oWBB
。此外,它不是线程-安全。如果您使用 ConcurrentDictionary 相反,
这是重写代码的示例:
In your current code, you are not checking the correct item for existence (you are checking
oWBB.Browser
, but you should be checkingoWBB
. In addition, it is not thread-safe.It would be easier to verify the items existence in a threadsafe manner if you used a ConcurrentDictionary instead.
Here's an example of the rewritten code:
您必须锁定非线程安全的资源。这可确保在给定时间只有一个线程正在访问它们。
You have to lock the resources that are not thread safe. This ensures that only one thread is accessing them at a given time.