c# - Run a C# method in separate Task to avoid delay
问题描述
I am working on a C# application. I have a method which runs at the start of the application, this method takes sometime due to which there is delay in application start. To overcome this i want to run that method in a separate task/thread, so that my application gets started and this method continues to run on separate thread.
Current implementation of my method is:
public void Start()
{
ManagementObjectCollection ManObjReturn;
ManagementObjectSearcher ManObjSearch;
ManObjSearch = new ManagementObjectSearcher("SELECT * FROM Win32_PnPEntity WHERE ClassGuid=\"{4d36e978-e325-11ce-bfc1-08002be10318}\"");
ManObjReturn = ManObjSearch.Get();
foreach (ManagementObject ManObj in ManObjReturn)
{
string name = ManObj["Name"].ToString();
int i = name.LastIndexOf('(');
string port = name.Substring(i + 1, name.Length - i - 2);
string man = ManObj["Manufacturer"].ToString();
for (int x = 0; x < allComPorts.Count; x++)
{
if (string.Equals(man, "FTDI") && string.Equals(port, UsbState.allComPorts[x]))
{
FtdiDevice ftdiDevice = new FtdiDevice() { ComPortName = allComPorts[x] };
existingFtdiPorts.Add(ftdiDevice);
OnDeviceAttached(this, new FtdiDeviceEventArgs() { ftdiDevice = ftdiDevice });
break;
}
}
}
BackgroundWorker bgwUsbDeviceDetector = new BackgroundWorker();
bgwUsbDeviceDetector.DoWork += UsbDeviceDetection;
bgwUsbDeviceDetector.RunWorkerAsync();
bgwUsbDeviceDetector.WorkerReportsProgress = true;
bgwUsbDeviceDetector.WorkerSupportsCancellation = true;
}
After searching on the google, what i get is that we can use Task.Run for running on the separate task/thread.
Now my update code is:
public void Start()
{
Task.Run(() => (
ManagementObjectCollection ManObjReturn;
ManagementObjectSearcher ManObjSearch;
ManObjSearch = new ManagementObjectSearcher("SELECT * FROM Win32_PnPEntity WHERE ClassGuid=\"{4d36e978-e325-11ce-bfc1-08002be10318}\"");
ManObjReturn = ManObjSearch.Get();
foreach (ManagementObject ManObj in ManObjReturn)
{
string name = ManObj["Name"].ToString();
int i = name.LastIndexOf('(');
string port = name.Substring(i + 1, name.Length - i - 2);
string man = ManObj["Manufacturer"].ToString();
for (int x = 0; x < allComPorts.Count; x++)
{
if (string.Equals(man, "FTDI") && string.Equals(port, UsbState.allComPorts[x]))
{
FtdiDevice ftdiDevice = new FtdiDevice() { ComPortName = allComPorts[x] };
existingFtdiPorts.Add(ftdiDevice);
OnDeviceAttached(this, new FtdiDeviceEventArgs() { ftdiDevice = ftdiDevice });
break;
}
}
}
BackgroundWorker bgwUsbDeviceDetector = new BackgroundWorker();
bgwUsbDeviceDetector.DoWork += UsbDeviceDetection;
bgwUsbDeviceDetector.RunWorkerAsync();
bgwUsbDeviceDetector.WorkerReportsProgress = true;
bgwUsbDeviceDetector.WorkerSupportsCancellation = true;
)
}
But this does not work and i get the error ManagementObjectCollection is a type which is not valid in the given context
Can anybody help me ? I know i am missing something really simple regarding Task and how to use them, but any help would be really appreciated.
解决方案
像这样的东西(只是你的基础)
public async Task<yourType> MyMethod()
{
...your code...
return await Task.Run(()=> yourType.-any extension method if you need it-;)
}
推荐阅读
- java - 如何增加andriod studio中的媒体音量?
- azure - Azure CosmosDB:文档 ID 中的非法字符
- postgresql - 为什么数据库连接会自动关闭?
- android - 尝试在销毁时重新启动应用程序并使其保持运行
- ruby-on-rails - 如何显示从 Mongoid::GridFs 返回的图像
- python - 了解 python 'for' 关键字的不同用途
- c# - 实体框架核心多个外键同表错误
- html - 使用 html js 和 css 制作一个具有 5 个电子的原子预加载器
- node.js - 是否可以在 nodejs 应用程序中创建完全独立的模块?
- reactjs - React.JS 中的无效 Hook 调用