How to use Thread to release the application from freezing in c#

淺唱寂寞╮ 提交于 2020-01-24 22:12:12

问题


I have the code below for scanning but When i press the button to start scanning, the windows form freezes and i can not move the form or minimizie/colse it until the process will be finished! i'm new in working with Thread but i tried to add Thread andi couldn't solve the problem. Does anyone know to where (how) can i write a Thread to release my form from freezing? Thanks.

public Bitmap GetBitmapFromRawData(int w, int h, byte[] data)
{
   //Do sth
 }
    //button to start the scan proccess
    private void button1_Click(object sender, EventArgs e)
    {
      try
      {
        var deviceManager = new DeviceManager();
        for ( int i = 1; i <= deviceManager.DeviceInfos.Count; i++ ) 
        {
          if ( deviceManager.DeviceInfos[i].Type != WiaDeviceType.ScannerDeviceType ) 
          {
            continue;
          }
          lstListOfScanner.Items.Add(deviceManager.DeviceInfos[i].Properties["Name"].get_Value());
        }
      }
      catch ( COMException ex )
      {
        MessageBox.Show(ex.Message);
      }

      try
      {
        var deviceManager = new DeviceManager();

        DeviceInfo AvailableScanner = null;

        for ( int i = 1; i <= deviceManager.DeviceInfos.Count; i++ ) 
        {
          if ( deviceManager.DeviceInfos[i].Type != WiaDeviceType.ScannerDeviceType ) // Skip device If it is not a scanner
          {
            continue;
          }

          AvailableScanner = deviceManager.DeviceInfos[i];
          break;
        }
        var device = AvailableScanner.Connect(); 
        var ScanerItem = device.Items[1];
        var imgFile = (ImageFile)ScanerItem.Transfer();
        var data = (byte[])imgFile.FileData.get_BinaryData();
        var bitmap = GetBitmapFromRawData(imgFile.Width, imgFile.Height, data);
        var Path = @"C:\....\ScanImg.jpg"; 
        bitmap.Save(Path, ImageFormat.Jpeg);
      }
      catch ( COMException ex )
      {
        MessageBox.Show(ex.Message);
      }

回答1:


Try adopting the async/await approach:

private async void button1_Click(object sender, EventArgs e)
{
    try
    {
        object[] items = await Task.Run<object[]>(() =>
        {
            var deviceManager = new DeviceManager();
            List<object> result = new List<object>();
            for (int i = 1; i <= deviceManager.DeviceInfos.Count; i++)
            {
                if (deviceManager.DeviceInfos[i].Type != WiaDeviceType.ScannerDeviceType)
                {
                    continue;
                }
                result.Add(deviceManager.DeviceInfos[i].Properties["Name"].get_Value());
            }
            return result.ToArray();
        });
        foreach (var item in items)
        {
            lstListOfScanner.Items.Add(item);
        }
    }
    catch (COMException ex)
    {
        MessageBox.Show(ex.Message);
    }

    try
    {
        await Task.Run(() =>
        {
            var deviceManager = new DeviceManager();

            DeviceInfo AvailableScanner = null;

            for (int i = 1; i <= deviceManager.DeviceInfos.Count; i++)
            {
                if (deviceManager.DeviceInfos[i].Type != WiaDeviceType.ScannerDeviceType) // Skip device If it is not a scanner
                {
                    continue;
                }

                AvailableScanner = deviceManager.DeviceInfos[i];
                break;
            }
            var device = AvailableScanner.Connect();
            var ScanerItem = device.Items[1];
            var imgFile = (ImageFile)ScanerItem.Transfer();
            var data = (byte[])imgFile.FileData.get_BinaryData();
            var bitmap = GetBitmapFromRawData(imgFile.Width, imgFile.Height, data);
            var Path = @"C:\....\ScanImg.jpg";
            bitmap.Save(Path, ImageFormat.Jpeg);
        });
    }
    catch (COMException ex)
    {
        MessageBox.Show(ex.Message);
    }
}


来源:https://stackoverflow.com/questions/58873895/how-to-use-thread-to-release-the-application-from-freezing-in-c-sharp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!