【发布时间】:2020-05-03 04:10:25
【问题描述】:
我有一个方法,我打算在它自己的线程上运行,但在设置线程时不知道如何传递引用。
private void ManageConnections(ref List<string> instanceAddresses)
{
int connected = Instances.Count();
if(instanceAddresses.Count() > connected)
{
int instancesToAdd = instanceAddresses.Count() - connected;
while(instancesToAdd != 0)
{
Channel channel = new Channel(instanceAddresses[instanceAddresses.Count - instancesToAdd], ChannelCredentials.Insecure);
var client = new ConfigurationDirectoryService.ConfigurationDirectoryServiceClient(channel);
Instances.Add(client);
instancesToAdd--;
}
}
}
期望的行为是,当原始列表(instanceAddresses)更改时,此方法可以开始工作,并且可以设置新客户端并将其添加到另一个列表中。
这是调用线程启动的方法:
public CDS_Service(ref List<string> instanceAddresses)
{
Thread manageAvaliable = new Thread(CheckAvaliability);
manageAvaliable.Start();
if(instanceAddresses.Count() > 0)
{
foreach(string instanceAddr in instanceAddresses)
{
Channel channel = new Channel(instanceAddr, ChannelCredentials.Insecure);
var client = new ConfigurationDirectoryService.ConfigurationDirectoryServiceClient(channel);
Instances.Add(client);
}
foreach(CM commandManager in Instances[0].SyncDirectory(new Empty { }).CommandManagers)
{
List<string> commands = new List<string>();
foreach(string command in commandManager.Commands)
{
commands.Add(command);
}
Directory.Add(new CommandManager(commandManager.Address, commands, commandManager.IsActive));
}
}
//Thread would be setup here
}
这是在哪里构造的:
Server server = new Server
{
Services = { ConfigurationDirectoryService.BindService(new CDS_Service(ref clientDiscovery.OtherInstances)) },
Ports = { new ServerPort(addr, PORT, ServerCredentials.Insecure) }
};
我也不确定这是否也是通过不同类传递 ref 的不好做法。
这可能/安全吗?
【问题讨论】:
-
这不是你应该使用传递引用的地方。您应该使用可观察的集合。
-
@Sweeper 谢谢,不知道这是一回事。但是,我将这个列表作为构造函数传递给这个类,因为它来自其他地方。同样,不确定这是否是不好的做法。
-
能否也显示方法的调用方?
-
那您打算在
//Thread would be setup here线上拨打ManageCollections吗?您还没有显示instanceAddresses的来源。基本上,无论它来自哪里,都将其更改为ObservableCollection<string>。 -
@Sweeper 抱歉,不清楚,是的,那里会调用 ManageCollections。 instanceAddreses 是在构造函数中传递的引用(参见底部的 sn-p)。它来自另一个类(clientDiscovery)
标签: c# multithreading reference ref