How to use an AppDomain to limit a static class' scope for thread-safe use?

后端 未结 6 2033
我在风中等你
我在风中等你 2021-01-05 10:31

I have been bitten by a poorly architected solution. It is not thread safe!

I have several shared classes and members in the solution, and during development all

6条回答
  •  生来不讨喜
    2021-01-05 11:07

    Using app domains you could do something like this:

    public class Loader
    {
    
        private string connectionString;
        private string fileName;
        private Stream stream;
        private DataFile dataFile;
    
        public Loader(Stream stream, string fileName, string connectionString)
        {
            this.connectionString = connectionString;
            this.fileName = fileName;
            this.stream = stream;
        }  
    
        public void Process()
        {
            //*****  Create AppDomain HERE *****
            string threadID = Thread.CurrentThread.ManagedThreadId.ToString();
            AppDomain appDomain = AppDomain.CreateDomain(threadID);
    
            DataFile dataFile = 
                (DataFile) appDomain.CreateInstanceAndUnwrap(
                            "", 
                            "DataFile", 
                            true, 
                            BindingFlags.Default,
                            null,
                            new object[] 
                            { 
                                aredstream, 
                                filename, 
                                connectionString 
                            },
                            null,
                            null,
                            null);
            dataFile.ParseFile();
            dataFile.Save();
    
            appDomain.Unload(threadID);       
        }
    }
    

提交回复
热议问题