Keep variable in memory until system reboot

3

Is there a way to keep a variable in the machine's memory until it restarts?

My application made a change in the system and sent the message to the user to restart the machine, to prevent any problems I have to detect if the machine has already been restarted even if you close the program and start again.

I figured that maybe I could use an address in memory to check that the machine needs to restart and store the address of that variable in the application settings, so even if they reboot the program it would test if the memory location indicates that it needs to restart ...

As I have little knowledge in the more "low-level" area of C # I do not know if it would actually store the variable or if there is a correct way to do it.     

asked by anonymous 28.07.2016 / 04:01

2 answers

6

Marcus, as bigown pointed out, it is not possible to keep a variable in memory, however you can save a flag stating that the system needs to be restarted, so the easiest solution is to change app.config

var config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
config.AppSettings.Settings["Restart"].Value = "true";
config.AppSettings.Settings["Data"].Value = DateTime.Now.ToString("o");
config.Save(ConfigurationSaveMode.Modified);

If you need more data, you can choose to store a JSON file in some system folder (the example below uses Newtonsoft.Json ):

var dados = new { MustRestart = true, Data = DateTime.Now, Foo = "Hello", Bar = "World" };
var json = JsonConvert.SerializeObject(dados);
System.IO.File.WriteAllText(AppDomain.CurrentDomain.BaseDirectory + "\dados.json", json);

If you have some kind of paranoia and want to prevent the user from modifying these values, you have two options, storing this data using Sqlite with SQLite Encryption Extension (SEE). you can see more about it in.:

Finally you can send a request to a WebAPI and it will update a flag stating that the machine needs to be restarted, this approach has two negative points, the client needs an internet connection and you need to implement and host WebAPI .

As to whether the machine has been restarted, you can read the Windows logs in the following way, then you just have to look at the entries:

var eventLog = new System.Diagnostics.EventLog(); 
//eventLog.Source = ""; O ideal que informe o nome do Log que possui os eventos de inicialização do sistema.
foreach (var entry in eventLog.Entries) 
{
   Console.WriteLine(entry.Message);
}
    
28.07.2016 / 14:45
4

I find this somewhat strange, it seems to me that the solution to the problem should even be other. But answering the question, it is not possible in C # or in any language to keep application data in memory when it is not running.

But you can get the same result by keeping data in a file. What does not have anything low level.

    
28.07.2016 / 04:11