Det er en vesentlig enklere måte å få dette til med en mutex:
using System;
using System.Threading;
using System.Windows.Forms;
namespace SingleInstance
{
static class Program
{
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
var mutex = new Mutex(false, "MyApplication");
if (mutex.WaitOne(0))
{
try
{
Application.Run(new Form1());
}
finally
{
mutex.ReleaseMutex();
}
}
}
}
}
Det er strengt tatt ikke nødvendig med den finally saken.
var deviceList = new ManagementObjectSearcher("Select Name, Status from Win32_PnPEntity");
var allIsOk = deviceList.Get().Cast<ManagementObject>().All(device => (string)device.GetPropertyValue("Status") == "OK");
if(allIsOk)
{
// Do something
}Her er en som fjerner alle elementer uten status også:
var deviceList = new ManagementObjectSearcher("Select Name, Status from Win32_PnPEntity");
var statuses = from device in deviceList.Get().Cast<ManagementObject>()
let status = (string)device.GetPropertyValue("Status")
where !string.IsNullOrEmpty(status)
select status;
var isAllOk = statuses.All(status => status == "OK");
if(allIsOk)
{
// Do something
}Noe kode som skriver ut mer info:
var deviceList = new ManagementObjectSearcher("Select Name, Status from Win32_PnPEntity");
var statuses = from device in deviceList.Get().Cast<ManagementObject>()
let status = (string)device.GetPropertyValue("Status")
where !string.IsNullOrEmpty(status)
select new { Status = status, Name = (string)device.GetPropertyValue("Name") };
var isAllOk = statuses.All(device => device.Status == "OK");
Console.Write("Is all OK? ");
Console.WriteLine(isAllOk ? "Yes!" : "No.");
foreach(var device in statuses.Where(d => d.Status != "OK"))
Console.WriteLine("{0}: {1}", device.Name, device.Status);