I hava a program that needs to run any threads at the same time. I don't know what is the best way to inject the same services in any thread and don't care about concurrency exception.
For example:
Console Main
public class Program
{
static void Main()
{
IUnityContainer container = new UnityContainer();
container.RegisterType<IMySharedService, MySharedService>(new PerThreadLifetimeManager());
ProgramService service = container.Resolve<ProgramService>();
service.Run();
}
}
public class ProgramService : IProgramService
{
public static ConcurrentQueue<string> queue = new ConcurrentQueue<string>();
private readonly IMySharedService _mySharedService;
public ProgramService(IMySharedService mySharedService)
{
_mySharedService = mySharedService;
}
public void Run()
{
FirstThread firstThread = new FirstThread(_mySharedService);
SecondThread secondThread = new SecondThread(_mySharedService);
firstThread.Start();
secondThread.Start();
while (!_shouldStop)
{
string message;
if (queue.TryDequeue(out message))
{
firstThread.DoSomething(message);
secondThread.DoSomething(message);
}
System.Threading.Thread.Sleep(250);
}
}
}
In MySharedService I use to find some object (like UserModel) and the service return null object. I believe that some concurrency error are invalidating the object.
Someone have some design pattern for this kind of example?
Aucun commentaire:
Enregistrer un commentaire