C# 如何在另一个线程中运行和处理表单?

发布于 2024-09-15 02:05:06 字数 330 浏览 2 评论 0原文

这是我的问题:我正在用 C# 制作产品上传模块(主窗体)。我从 Excel 文件读取数据,然后上传到数据库,然后调整图像大小并通过 FTP 上传。一切正常。现在我想添加一个进度条。我制作了一个新表单,添加了两个进度条,并创建了为进度条赋予新值的公共方法,以及第三个方法,用于在完成时输出文本。如果我将它的一个实例放入主窗体中,它可以工作,但我正在进行困难操作(调整图像大小、上传到 ftp),并且 CPU 无法跟踪进度条的变化速度。因此,解决方案是在新线程中启动进度表。我尝试了很多不同的方法来做到这一点,但没有成功。主要问题是我应该从主窗体触发进度窗体的公共方法。

我以前从未在 C# 中制作过进度条,你能告诉我哪种方法最简单?

Here's my problem: I'm making a product upload module (main form) in C#. I read data from excell files, then upload into database, then I'm resizeing the images and uploading via FTP. Everything works fine. Now I want to add a progress bar. I've made a new form, I've add two progress bars, and made public methods for giving new value to the progress bars, and a third method, to output a text when finished. If I place an instance of it into the main form, it works, but I am making hard operations (resizeing image, uploading into ftp) and the CPU can't trace the progressbar as fast as it changes. So the solution would be to start the progress form in a new thread. I have tried many different ways to do it but without success. The main problem is that I should trigger the public methods of the progress form from the main form.

I have never made progressbars in c# before, can you tell me please which is the easiest and simplest way to do it?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

撩人痒 2024-09-22 02:05:06

我认为也许您最好在单独的线程中执行密集操作,然后将事件编组回进度表单,以便向用户显示进度。

当您有单独的线程时,您不能只从这些线程更新 GUI。你应该看看使用 Invoke
MSDN

此示例还展示了如何使用工作线程来执行更密集的任务的简单示例。

   private void Button_Click(object sender, EventArgs e)
  {
     myThread = new Thread(new ThreadStart(ThreadFunction));
     myThread.Start();
  }
  private void ThreadFunction()
  {
     MyThreadClass myThreadClassObject  = new MyThreadClass(this);
     myThreadClassObject.Run();
  }

I think perhaps you would be best performing the the intensive actions in the separate thread and then marshal events back to your progress form in order to display to the user the progress.

When you have separate threads you can't just update the GUI from those threads. You should look at using Invoke
MSDN.

This example also shows a simple example of how you can use a worker thread to perform your more intensive tasks.

   private void Button_Click(object sender, EventArgs e)
  {
     myThread = new Thread(new ThreadStart(ThreadFunction));
     myThread.Start();
  }
  private void ThreadFunction()
  {
     MyThreadClass myThreadClassObject  = new MyThreadClass(this);
     myThreadClassObject.Run();
  }
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文