操作繁忙时表单不执行任何操作(冻结) [英] Form does not do anything (freezes) while an operation is busy

查看:30
本文介绍了操作繁忙时表单不执行任何操作(冻结)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个使用 C# 的 WinForms 应用程序.我尝试从文件中读取一些数据并将其插入到数据表中.当这个操作很忙时,我的表单冻结了,我无法移动它.有谁知道我该如何解决这个问题?

I have a WinForms application using C#. I try to read some data from a file and insert it into a datatable. While this operation is busy, my form freezes and I can't event move it. Does anyone know how I can solve this problem?

推荐答案

这可能是因为您在 UI 线程上进行操作.

This might be because you do the operation on your UI Thread.

将文件和数据库操作移动到另一个线程以防止您的 UI 线程冻结.

Move the File and Database actions to another thread to prevent your UI Thread from freezing.

这是一个使用线程池的示例.作为替代方案,您可以手动启动线程,但如果您例如,则需要手动跟踪它们.想要中止它们等等.

Here is an example using the ThreadPool. As an alternative you can manually start Threads but then you need to keep track of them manually if you e.g. want to abort them etc.

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Threading;

namespace WindowsFormsApplication1
{
   public partial class Form1 : Form
   {
      public Form1()
      {
         InitializeComponent();
      }

      private void Form1_Load(object sender, EventArgs e)
      {
         // With ThreadPool
         ThreadPool.QueueUserWorkItem(DoWork);
      }

      private void DoWork(object state)
      {
         // Do Expensive Work
         for (int i = 0; i < 100; i++)
         {
            Thread.Sleep(10);
         }
         System.Diagnostics.Debug.WriteLine("DoWork finished!");
      }

   }
}

这篇关于操作繁忙时表单不执行任何操作(冻结)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆