如何初始化和使用静态类
本文关键字:静态类 初始化 | 更新日期: 2023-09-27 17:49:25
我有一个静态类,用于访问静态concurrentdictionary:
public static class LinkProvider
{
private static ConcurrentDictionary<String, APNLink.Link> deviceLinks;
static LinkProvider()
{
int numProcs = Environment.ProcessorCount;
int concurrencyLevel = numProcs * 2;
deviceLinks = new ConcurrentDictionary<string, APNLink.Link>(concurrencyLevel, 64);
}
public APNLink.Link getDeviceLink(string deviceId, string userId)
{
var result = deviceLinks.First(x => x.Key == deviceId).Value;
if (result == null)
{
var link = new APNLink.Link(username, accountCode, new APNLink.DeviceType());
deviceLinks.TryAdd(deviceId, link);
return link;
}
else
{
return result;
}
}
public bool RemoveLink(string deviceId)
{
//not implmented
return false;
}
}
如何在asp.net控制器中使用该类
我想去:
LinkProvider provider;
APNLink.Link tmpLink = provider.getDeviceLink(id, User.Identity.Name);
//use my link
背景。字典用于在asp.net web api程序中保存状态/请求之间的链接对象。因此,当服务需要使用链接时,它要求链接提供程序为它找到一个链接,如果没有,它必须创建一个。因此,我需要在所有http请求中使用相同实例的dictionary对象
所以我需要字典对象到我所有的http的相同实例请求
然后使用static
类,并将每个方法也设置为static
,因此您可以使用以下语法调用它:
APNLink.Link tmpLink = LinkProvider.getDeviceLink(id, User.Identity.Name);
也就是说,您应该意识到ASP中内存中的静态变量。Net应用程序并不总是可以安全地使用,因为您的应用程序不是无状态的,并且如果应用程序池被回收,您的字典将被重新实例化。