Making a program with singletons multithreaded C#

 ̄綄美尐妖づ 提交于 2019-12-06 11:55:06

The easiest way is to move all calculations to one separate thread and update the GUI using Invoke/InvokeRequired.

public partial class MyForm : Form
{
    Thread _workerThread;

    public MyForm()
    {
        _workerThread = new Thread(Calculate);
    }

    public void StartCalc()
    {
        _workerThread.Start();
    }

    public void Calculate()
    {
        //call singleton here


    }

    // true if user are allowed to change calc settings
    public bool CanUpdateSettings
    {
        get { return !_workerThread.IsAlive; } }
    }
}

In this way you have get a response GUI while the calculations are running.

The application will be thread safe as long as you don't allow the user to make changes during a running calculation.

Using several threads for doing the calculations is a much more complex story which we need more information for to give you a proper answer.

Generally, I avoid the singleton pattern because it creates a lot of issues down the road, particularly in testing. However, there is a fairly simple solution to making this work for multiple threads, if what you want is a singleton per thread. Put your singleton reference in a field (not a property) and decorate it with the ThreadStaticAttribute:

public class MySingleton
{
   [ThreadStatic]
   private static MySingletonClass _instance = new MySingletonClass();
   public static MySingletonClass Instance { get { return _instance; } }
}

Now each thread will have its own instance of MySingleton.

You can use TPL

You can make the loops with TPL parallel, and further more it is built-in with .NET 4.0 so that you don't have to change your program so much

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!