我如何实现线程 [英] how can i implement threads

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

问题描述

我的程序没有响应可以帮助我,以便我可以在我的程序中实现线程

my program is not responding can any one help me so that i can implement threads in my program

推荐答案

最简单的方法:

Simplest way:

BackgroundWorker bw;
private void button1_Click(object sender, EventArgs e)
    {
    bw = new BackgroundWorker();
    bw.WorkerSupportsCancellation = true;
    bw.DoWork += new DoWorkEventHandler(bw_DoWork);
    bw.RunWorkerAsync();
    }

void bw_DoWork(object sender, DoWorkEventArgs e)
    {
    BackgroundWorker worker = sender as BackgroundWorker;
    int i = 0;
    while (true)
        {
        if (worker.CancellationPending == true)
            {
            e.Cancel = true;
            break;
            }
        else
            {
            Console.WriteLine(i++);
            System.Threading.Thread.Sleep(500);
            }
        }
    }

private void button2_Click(object sender, EventArgs e)
    {
    if (bw.IsBusy)
        {
        bw.CancelAsync();
        }
    }

请记住,除了原始线程外,您无法与UI元素进行交互-您需要为此调用控件.

Do bear in mind that you can''t interact with UI elements except on the original thread - you will need to invoke the controls for that.


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

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