我正在为集中式服务器开发一个打印队列,它负责根据需要将打印作业定向到不同的服务器。
我这样做是作为一个WCF服务,它有一个"Print“端点。这一切都很好,我已经设置好了,但是我正在尝试开发一个线程安全端点,它也可以返回排队线程数量的计数。
下面是一个示例类,它触发多个线程并将它们发送到"Print“方法(它模拟多个人同时到达端点的行为)。
public class ThreadStuff
{
#region [Singleton Logic]
private static ThreadStuff _instance;
private ThreadStuff() { }
private static ThreadStuff Instance
{
get { return _instance ?? (_instance = new ThreadStuff()); }
}
#endregion
private static readonly object LockObject = new object();
private int _queuedThreads;
public static int QueuedThreads
{
get { return Instance._queuedThreads; }
}
public static void Start()
{
var threads = new Thread[10];
for (var i = 0; i < 10; i++)
{
var threadNumber = i;
var t = new Thread(() => Instance.MyMethod(threadNumber));
threads[i] = t;
}
for (var i = 0; i < 10; i++)
{
var threadNumber = i;
Thread.Sleep(50);
threads[i].Start();
Console.WriteLine("Thread {0} started", threadNumber);
}
Console.ReadKey();
}
private void MyMethod(int threadNumber)
{
Console.WriteLine("Thread {0} entered MyMethod", threadNumber);
Instance._queuedThreads++;
lock (LockObject)
{
Console.WriteLine("Thread {0} entered MyMethod's Lock", threadNumber);
Thread.Sleep(2000);
Console.WriteLine("Thread {0} finished Thread.Sleep", threadNumber);
}
Instance._queuedThreads--;
Console.WriteLine("Thread {0} exited MyMethod", threadNumber);
}
}这项工作如预期的那样进行,产生了以下成果:

但是,我随后将另一个项目添加到我的解决方案中,它将访问这个单例的"QueuedThreads“属性(模拟轮询端点的行为)。
这个项目是一个简单的win应用程序,有以下代码
textBox1.Text = ThreadStuff.QueuedThreads.ToString(CultureInfo.InvariantCulture);但是,这总是返回0,winforms应用程序无法看到" ThreadStuff“类的Singleton数据,它会创建一个新的ThreadStuff实例。我已经在我的办公室周围敲了一下,没有人知道为什么会发生这种情况,在多次搜索谷歌之后,我决定在这里询问。
任何帮助都将不胜感激。
发布于 2014-01-09 12:31:34
这种情况可能是因为它是两个不同的进程,一个控制台应用程序和一个WinForm应用程序。只要是这样,您就需要某种类型的进程间通信来使WinForm应用程序能够看到排队的请求。有几种方法可以做到这一点。几种可能性
发布于 2014-01-09 12:09:43
尝试以下模式:
using System;
public sealed class Singleton
{
private static volatile Singleton instance;
private static object syncRoot = new Object();
private Singleton() {}
public static Singleton Instance
{
get
{
if (instance == null)
{
lock (syncRoot)
{
if (instance == null)
instance = new Singleton();
}
}
return instance;
}
}
}https://stackoverflow.com/questions/21019314
复制相似问题