首页 > 解决方案 > 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.

标签: c#asynchronoustask

解决方案


像这样的东西(只是你的基础)

 public async Task<yourType> MyMethod() 
 {
    ...your code...
    return await Task.Run(()=> yourType.-any extension method if you need it-;)
 }

推荐阅读