因此,我正在考虑建立一个业余爱好项目,一种类似的东西,只是为了了解我的编程/设计.
它基本上是一个多线程的Web蜘蛛,更新相同的数据结构对象 - > int.
因此,为此使用数据库绝对有点过分,我唯一能想到的是用于包含我的数据结构的线程安全单例.http://web.archive.org/web/20121106190537/http://www.ibm.com/developerworks/java/library/j-dcl/index.html
我应该注意一个不同的方法吗?
在我们的SharePoint/ASP.NET环境中,我们有一系列数据检索器类,这些类都来自通用接口.我被分配了创建数据检索器的任务,该数据检索器可以使用WCF与其他SharePoint场远程通信.我现在实现它的方式ChannelFactory<T>是在静态构造函数中创建单例,然后由远程数据检索器的每个实例重用,以创建单独的代理实例.我认为这样可以很好地工作,因为那时ChannelFactory只在app域中实例化一次并且它的创建保证是线程安全的.我的代码看起来像这样:
public class RemoteDataRetriever : IDataRetriever
{
protected static readonly ChannelFactory<IRemoteDataProvider>
RequestChannelFactory;
protected IRemoteDataProvider _channel;
static RemoteDataRetriever()
{
WSHttpBinding binding = new WSHttpBinding(
SecurityMode.TransportWithMessageCredential, true);
binding.Security.Transport.ClientCredentialType =
HttpClientCredentialType.None;
binding.Security.Message.ClientCredentialType =
MessageCredentialType.Windows;
RequestChannelFactory =
new ChannelFactory<IRemoteDataProvider>(binding);
}
public RemoteDataRetriever(string endpointAddress)
{
_channel = RemoteDataRetriever.RequestChannelFactory.
CreateChannel(new EndpointAddress(endpointAddress));
}
}
Run Code Online (Sandbox Code Playgroud)
我的问题是,这是一个很好的设计吗?我想,一旦ChannelFactory创建,我不需要担心线程安全,因为我只是用它来打电话,CreateChannel()但我错了吗?它是在改变状态还是在幕后做一些可能导致线程问题的时髦的东西?另外,我是否需要在某个地方放置一些代码(静态终结器?)来手动处理ChannelFactory或者我可以假设每当IIS重新启动它时,它会为我做所有的清理工作吗?
wcf singleton static-constructor thread-safety channelfactory
我有一个类似于此的单例类
public class Singleton
{
private static Singleton m_instance;
private Timer m_timer;
private static List<CustomObject> m_cacheObjects;
private Singleton()
{
m_cacheObjects = new List<CustomObject>();
m_timer= new Timer(MyTimerCallBack,
null,
TimeSpan.FromSeconds(60),
TimeSpan.FromSeconds(60));
}
public static Singleton Instance
{
get
{
if (m_instance == null)
{
m_instance = new Singleton();
}
return m_instance;
}
}
private void MyTimerCallBack(object state)
{
//******** Update the list by interval here ******************
m_cacheObjects = UpdateTheList();
}
public void CallMe()
{
foreach (CustomObject obj in m_cacheObjects)
{
// do …Run Code Online (Sandbox Code Playgroud) 尽管有关该主题的许多主题,我仍然不清楚何时选择哪种方法.我希望通过讨论一个具体的例子,我终于"明白了".
注意:我的语言是Cocoa,尽管一般问题不是语言特定的.
我有一个类TaskQueue,我想用它:
首次使用TaskQueue时,我希望TaskQueue启动一个线程,然后定期唤醒该线程来处理任务.
显然,我至少需要两个变量:
由于我只需要一个任务队列和一个线程来处理这些任务,我有两个选择:
做任务队列一个单独的类(如描述例如使用CWL_DECLARE_SINGLETON_FOR_CLASS_WITH_ACCESSOR http://www.cocoawithlove.com/2008/11/singletons-appdelegates-and-top-level.html,我相信我将不得不修改CWLSynthesizeSingleton. h文件在初始化时启动线程.)
让任务数组和线程实例都是静态的(遵循这里建议的方法:如何在Objective-C中声明类级属性?)
在这个特定情况下,是否有一种方法比另一种方法更好?如果是这样,为什么?
有多个源调用特定方法,但我想确保它被调用一次(每个对象)
我想使用类似的语法
// method called possibly from multiple places (threads)
-(void)finish
{
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
[self _finishOnce]; // should happen once per object
});
}
// should only happen once per object
-(void)_finishOnce{...}
Run Code Online (Sandbox Code Playgroud)
问题是令牌是在同一个类的所有实例中共享的 - 所以不是一个好的解决方案 - 每个对象是否有dispatch_once_t - 如果不是,确保它被调用一次的最佳方法是什么?
编辑:
这是我想到的一个提议的解决方案 - 它看起来好吗?
@interface MyClass;
@property (nonatomic,strong) dispatch_queue_t dispatchOnceSerialQueue; // a serial queue for ordering of query to a ivar
@property (nonatomic) BOOL didRunExactlyOnceToken;
@end
@implementation MyClass
-(void)runExactlyOnceMethod
{
__block BOOL didAlreadyRun = NO;
dispatch_sync(self.dispatchOnceSerialQueue, ^{
didAlreadyRun …Run Code Online (Sandbox Code Playgroud) 对于2015年9月,这里正是你如何在Swift中创建一个单例:
public class Model
{
static let shared = Model()
// ( for ocd friends ... private init() {} )
func test()->Double
{
return 3.33
}
}
Run Code Online (Sandbox Code Playgroud)
其他地方......
// file ViewController.swift, say
import UIKit
class ViewController:UIViewController
{
override func viewDidLoad()
{
super.viewDidLoad()
print("view controller loaded!")
print("singleton test! \( Model.shared.test() )")
}
}
Run Code Online (Sandbox Code Playgroud)
没问题.
public let model = Model.shared
public class Model
{
static let shared = Model()
func test()->Double
{
return 3.33
}
}
Run Code Online (Sandbox Code Playgroud)
那么,你可以简单地在项目范围内进行以下操作:
class ViewController:UIViewController
{
override …Run Code Online (Sandbox Code Playgroud) 创建Service一个单独的工具是不好的做法?我的意思是一个Service永远不会停止,并包含一些其他引擎和Activities将使用的私人数据,所以Service可能有类似的东西:
public class CustomService extends Service {
private List<Profile> mProfiles;
private static CustomService instance;
public static CustomService getInstance() {
if(instance == null) {
instance = new CustomService();
}
return instance;
}
public List<Profile> getProfiles() {
return mProfiles;
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
...
}
...
}
Run Code Online (Sandbox Code Playgroud)
做一个Service而不仅仅是一个单例的原因是它必须独立于应用程序工作,因为它在启动时连接一个永远不应该关闭且不依赖于应用程序的websocket.你建议我做什么?有没有更好的方法来重新使用Service,以便mProfiles从其他引擎获得一些数据(例如数组)Activities?
我读过Service一个单独的工作,但我不知道如何从应用程序的任何其他点访问私有变量.
singleton android design-patterns android-service android-lifecycle
我添加了一个像这样的单例。
在 Startup.cs 中,我添加以下内容:
services.AddSingleton<MySingleton>();
Run Code Online (Sandbox Code Playgroud)
我想像这样构建我的单例(当然这是不可能的):
public class MySingleton
{
public MySingleton()
{
await InitAsync();
}
private async Task InitAsync()
{
await Stuff();
}
}
Run Code Online (Sandbox Code Playgroud)
如何在不造成僵局的情况下解决这个问题?
我读了这些帖子:
我在理解以下创建单例的方式之间的区别时遇到了一些麻烦:
1.工厂构造函数
class SingletonOne {
SingletonOne._privateConstructor();
static final SingletonOne _instance = SingletonOne._privateConstructor();
factory SingletonOne(){
return _instance;
}
}
Run Code Online (Sandbox Code Playgroud)
2.带有吸气剂的静态场
class SingletonTwo {
SingletonTwo._privateConstructor();
static final SingletonTwo _instance = SingletonTwo._privateConstructor();
static SingletonTwo get instance { return _instance;}
}
Run Code Online (Sandbox Code Playgroud)
3.静态场
class SingletonThree {
SingletonThree._privateConstructor();
static final SingletonThree instance = SingletonThree._privateConstructor();
}
Run Code Online (Sandbox Code Playgroud)
这些实例化如下:
SingletonOne one = SingletonOne();
SingletonTwo two = SingletonTwo.instance;
SingletonThree three = SingletonThree.instance;
Run Code Online (Sandbox Code Playgroud)
无需使用工厂构造函数。当new不是可选的时,工厂构造函数很方便,因为它
new MyClass()适用于每次构造函数都返回一个新实例或该类返回一个缓存实例的类。知道实际创建对象的方式和时间不是呼叫者的责任。
我不明白new现在可选是如何使工厂构造函数现在不必要。在您无法做类似SingletonTwo或 …
我使用 NextJS 生成静态页面列表。
所有页面都需要一个大的静态 Javascript 对象,该对象需要几分钟来初始化(它包含解析许多其他文件的结果)。
const bigData = initializeBigData(); // <- called for every page, instead once
export async function getStaticProps({ params }) {
return { bigData[params.slug] }; // ...
}
Run Code Online (Sandbox Code Playgroud)
不幸的是,我找不到一次初始化该数据对象的方法。initializeBigData()相反,每次创建页面时都会运行缓慢,这使得构建非常慢。
我尝试过以下操作:
npm run build --threads=1initializeBigData()所有这些都没有改变,在构建网站时,每个页面都会调用long 。
如果可能的话,我不想使用自定义服务器。
如何在 NextJS 项目的构建过程中只初始化一次对象?
singleton ×10
c# ×2
.net-core ×1
android ×1
asp.net-core ×1
asynchronous ×1
dart ×1
java ×1
next.js ×1
objective-c ×1
swift ×1
swift2 ×1
synchronized ×1
wcf ×1