关于一个函数的疑问
当运行下面这个类的GetMoc()函数时,如果网络连接好就没有问题,如果网络断开时运行就好久不出来,或者出现程序错误。
- C# code
using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Management;namespace haha{ public class haha { [System.Runtime.InteropServices.DllImport("kernel32.dll")] private static extern int GetVolumeInformation( string lpRootPathName, string lpVolumeNameBuffer, int nVolumeNameSize, ref int lpVolumeSerialNumber, int lpMaximumComponentLength, int lpFileSystemFlags, string lpFileSystemNameBuffer, int nFileSystemNameSize ); //此函数没有用,暂时没有删除 public string GetVolOf(string drvID) { const int MAX_FILENAME_LEN = 256; int retVal = 0; int a = 0; int b = 0; string str1 = null; string str2 = null; int i = GetVolumeInformation( drvID + @":\", str1, MAX_FILENAME_LEN, ref retVal, a, b, str2, MAX_FILENAME_LEN ); return retVal.ToString("x"); } public string[] GetMoc() { string[] str = new string[2]; ManagementClass mcHD = new ManagementClass("win32_logicaldisk"); ManagementObjectCollection mocHD = mcHD.GetInstances(); foreach (ManagementObject m in mocHD) { if (m["DeviceID"].ToString() == "C:") { str[1] = m["VolumeSerialNumber"].ToString(); break; } } return str; } }}
[解决办法]
把方法放到线程中去,有结果了再通知前台
[解决办法]
可能是 mcHD.GetInstances(); 里 用到了网络连接。
被管理的object与主机通过网络连接,网络正常时,主机可以循环
获取这些object 的 DeviceID 和 VolumeSerialNumber 等信息。
如果这时断网,程序可能出现你描述的那种情况。