线程Windows窗体 [英] Threading in Windows Forms

查看:450
本文介绍了线程Windows窗体的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在写的ASP.NET Web应用好几年了,但还没有真正上过大窗户,形成项目。我现在需要工作之一,所以我找了一些指针如何大的Windows窗体项目最好能结构。更具体地讲,我想知道如何处理多个线程。假设你有一个过程,需要一定的时间来完成 - 你不希望有UI窗口冻结并没有响应。使逻辑需要在一个单独的线程移动。如果该线程访问的用户界面,那么就会造成异常。调用似乎做的伎俩,但看起来很丑陋和繁琐的写入和读取!

I have been writing ASP.NET web application for years now, but haven't really worked on large windows forms projects. I now need to work on one, so I am looking on some pointers on how a large windows forms project should ideally be structured. More specifically, I would like to know how to handle multiple threads. Assume you have a process which takes some time to complete - you do not want to have the ui window frozen and not responding. So that logic needs to move in a separate thread. If this thread accesses the UI, then it will cause exceptions. Invoke seems to do the trick, but looks very ugly and cumbersome to write and read!

那么,在现实中,什么是最好的做法?人应该推出,以及如何这些线程的用户界面和逻辑之间划分什么类型的线程?任何样品code上手?

So, in reality, what are the best practices? What type of threads should one launch, and how should these threads be split between UI and logic? Any sample code to get started?

推荐答案

这里是一个简短的方式来使用的BackgroundWorker

here is a short way to use the backgroundworker

        public Form1()
    {
        InitializeComponent();

        BackgroundWorker worker = new BackgroundWorker();
        worker.WorkerReportsProgress = true; //set to true to fire the progress-changed event
        worker.DoWork += doWork;
        worker.ProgressChanged += progressChanged;
    }

    void progressChanged(object sender, ProgressChangedEventArgs e)
    {
        int progress = e.ProgressPercentage; //Progress-Value
        object userState = e.UserState; //can be used to pass values to the progress-changed-event
    }

    void doWork(object sender, DoWorkEventArgs e)
    {
        object argument = e.Argument; //Parameters for the call
        bool cancel = e.Cancel; //Boolean-Value for cancel work
        object result = e.Result; //Object for a return-value
    }

这篇关于线程Windows窗体的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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