开发者

How to prevent application hang during permissions check using WMI

开发者 https://www.devze.com 2023-02-19 06:08 出处:网络
I\'m using WMI, I need to get some information, but when class is not available due to insufficient permissions, everything hangs up for a few (~5) seconds. Even setting low timeout doesn\'t work (not

I'm using WMI, I need to get some information, but when class is not available due to insufficient permissions, everything hangs up for a few (~5) seconds. Even setting low timeout doesn't work (not to mention that it would be stupid solution).

Problem isn't insufficient permissions, problem is "hang up".

Is there any way to check if current process has privileges to read information from some class to prevent "hang up" and "access denied" exception?

ConnectionOptions co = new ConnectionOptions();
co.Impersonation = ImpersonationLevel.Impersonate;
co.Authentication = AuthenticationLevel.Packet;
co.Timeout = new TimeSpan(0, 0, 1); // 1 second, but still hangs for ~5
co.EnablePrivileges = false; // false or true, doesn't matter
ManagementPath mp = new ManagementPath();
mp.NamespacePath = @"root\CIMV2\Security\MicrosoftTpm";
mp.Ser开发者_运维问答ver = "";

ManagementScope ms = new ManagementScope(mp, co);
ms.Connect(); // Hangs for ~5 seconds and throws "access denied"


What you need to do is run the operation on a background thread. It may still take five seconds (or more) but your application will remain responsive instead of hanging. Try something like this:

  Task.Factory.StartNew(() =>
  {
    // Your permission checking code here.....
  }).ContinueWith((t) =>
  {
    // Inform user of permissions status.
  });

If you aren't using a version of the framework that supports 'Task' try a BackgroundWorker instead. These are common ways to keep long running processes from hanging your app.

0

精彩评论

暂无评论...
验证码 换一张
取 消