简体   繁体   English

C#BackgroundWorker和调用

[英]C# BackgroundWorker and Invoke

Can someone explain why invoking Thread.Sleep from BackgroundWorker blocks its execution. 有人可以解释为什么从BackgroundWorker调用Thread.Sleep阻止其执行。 Invoke should cause the delegate to be executed on the UI thread and background thread should continue with execution. 调用应导致委托在UI线程上执行,而后台线程应继续执行。 But that does not happen - why? 但这没有发生-为什么?

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
        BackgroundWorker bgrw = new BackgroundWorker();
        bgrw.DoWork += new DoWorkEventHandler(bgrw_DoWork);

        bgrw.RunWorkerAsync();
    }

    void bgrw_DoWork(object sender, DoWorkEventArgs e)
    {
        Console.WriteLine(DateTime.Now);
        this.Invoke(new Action(() => { Thread.Sleep(2000); })); //should be executed on the UI thread
        Console.WriteLine(DateTime.Now); // This line is executed after 2 seconds
    }       
}

It's a rather simple explanation. 这是一个相当简单的解释。 Invoke is a blocking call . Invoke阻止呼叫 If you want to queue work on the UI message loop asynchronously, use BeginInvoke instead: 如果要异步在UI消息循环上排队工作,请改用BeginInvoke

Executes the specified delegate asynchronously on the thread that the control's underlying handle was created on. 在创建控件的基础句柄的线程上异步执行指定的委托。

void bgrw_DoWork(object sender, DoWorkEventArgs e)
{
    Console.WriteLine(DateTime.Now);
    this.BeginInvoke(new Action(() => { Thread.Sleep(2000); })); 
    Console.WriteLine(DateTime.Now);
}  

Note your code, as currently constructed makes no sense. 注意您的代码,因为当前构造的没有意义。 I'm assuming you're using this for testing purposes. 我假设您将其用于测试目的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM