Agent_Smith
Agent_Smith

Reputation: 77

wpf detect clicked event finished without delaying main process

I need to detect a procedure from a click event has finished without delaying the main wpf process..

What I don't want

public void click_event(object sender,routedeventargs)
{
        <launch a bunch of threads>
        while(<threads.are alive>);


        <code for what i want to do after threads are done>
}

public void threadtask()
{}

what i just did

 public void click_event()
   {
         foreach(<thread>)
           <give thread task and start() each>
   }
   }

but this will not detect when the threads are done.. need help here. Thanks.

Upvotes: 0

Views: 196

Answers (2)

Jay
Jay

Reputation: 6294

Check out this article

public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
        this.ClickMe.Click += new RoutedEventHandler(ClickMe_Click);
    }

    void ClickMe_Click(object sender, RoutedEventArgs e)
    {
        BackgroundWorker bw = new BackgroundWorker();
        bw.DoWork += (workSender, workE) =>
        {
            string argument = (string)workE.Argument;
            // argument == "Some data"
            System.Threading.Thread.Sleep(2000);
        };

        bw.RunWorkerCompleted += new RunWorkerCompletedEventHandler(bw_RunWorkerCompleted);
        bw.RunWorkerAsync("Some data");
    }

    void bw_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
    {
        this.ResultsTextBlock.Text = "I'm done";
    }

}

Upvotes: 1

vcsjones
vcsjones

Reputation: 141588

You are asking for two different things. You want the main thread to not be blocked, but you want to do something when the other threads are done (which you have to wait for). Consider starting the threads from a new thread, then let that other thread do the work. Something like this:

public void click_event() 
{
    <start new thread>
         <foreach(thread in threads)>
            <do work>
         <join threads>
         <do your work here>
}

So all of the work is on a different thread, even the work you want to do afterward. Given that, do you need more than one worker thread anyway?

Upvotes: 1

Related Questions