本文介绍了从同一个文件读入程序的C#多个实例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 29岁程序员,3月因学历无情被辞! 我写了一个程序,它从文件读取,根据给定的参数进行处理和写入一些输出。我很好奇,如果当用户(通过打开可执行文件)创建我的程序的多个实例,并运行它们在同一个文件有可能出现的任何奇怪的问题。 我读从while循环和file.ReadLine()文件。 非常感谢你。 解决方案 The way this is worded leads me to think that you are concerned that the user might accidently run multiple instances of the program against the same file. If that is your concern, then you can prevent problems from this by opening the file in an exclusive mode. The operating system itself will ensure that only the single instance of the program has access to the file for as long as you hold the file open.If you access the file with a FileStream object, then I believe that exclusive mode is the default, so you don't have to worry about this at all. Just make sure your stream stays open through all the reads and writes for which consistency is required.If another instance of the program attempts to open the file, then it will throw a IOException and not allow the access. You can either let the program crash, or you can notify the user that the file is already being used and give them the option to choose another file, or whatever.UPDATEIf you want to read from the same file in many instances of the program, with no instance writing to it, then that is also easily doable. Just open the file in shared read-only mode, and there is no problem at all letting lots of programs read the file simultaneously.using (Stream stream = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.Read)) 这篇关于从同一个文件读入程序的C#多个实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 上岸,阿里云! 08-20 12:41