Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/318.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 窗体在操作繁忙时不执行任何操作(冻结)_C#_Winforms - Fatal编程技术网

C# 窗体在操作繁忙时不执行任何操作(冻结)

C# 窗体在操作繁忙时不执行任何操作(冻结),c#,winforms,C#,Winforms,我有一个使用C#的WinForms应用程序。我尝试从文件中读取一些数据并将其插入数据表。当此操作忙时,我的窗体冻结,无法移动它。有人知道我如何解决这个问题吗?这可能是因为您在UI线程上执行了该操作 将文件和数据库操作移动到另一个线程以防止UI线程冻结 下面是一个使用线程池的示例。 作为替代方案,您可以手动启动线程,但如果您想中止线程等,则需要手动跟踪它们 using System; using System.Collections.Generic; using System.ComponentM

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

这可能是因为您在UI线程上执行了该操作

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

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

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!");
      }

   }
}
使用系统;
使用System.Collections.Generic;
使用系统组件模型;
使用系统数据;
使用系统图;
使用System.Linq;
使用系统文本;
使用System.Windows.Forms;
使用系统线程;
命名空间Windows窗体应用程序1
{
公共部分类Form1:Form
{
公共表格1()
{
初始化组件();
}
私有void Form1\u加载(对象发送方、事件参数e)
{
//使用线程池
ThreadPool.QueueUserWorkItem(DoWork);
}
私有无效工作(对象状态)
{
//做昂贵的工作
对于(int i=0;i<100;i++)
{
睡眠(10);
}
System.Diagnostics.Debug.WriteLine(“DoWork finished!”);
}
}
}
利用。i、 e


这是因为您正在使用主线程执行耗时较长的操作。最好的解决方案是使用另一个线程读取所需的文件,这将允许正常更新主线程。
请阅读此处有关线程的详细信息您的UI相关控件在
UI线程上运行,通常,您不应该在UI线程上执行耗时的工作(如果这样做,您的UI线程将在该任务完成之前被阻塞/冻结)。
还有另一种类型的线程称为
工作线程
,您可以创建并使用它来执行长时间运行的任务,从而保持UI响应/不冻结


或者,Winforms中有一个
Backgroundworker组件
,您可以利用它在非UI线程上执行任务,这一点已经解释清楚了。

这让您很困惑。Teoman kardeşteşekkür ederim,ama kodunu bir az aıklar mısın,lütfen.我尝试此操作时出错:
委托“操作”不接受0个参数
,但当我删除
DoAfterActionIsComplete()
时,这对我有效+1这是我能够正确实施的唯一答案。
Task.Factory.StartNew(() => DoAction()).ContinueWith(() => DoAfterActionIsComplete());