简体   繁体   English

调用对话框并在backgroundworker中从中获取值?

[英]calling dialog and getting values from it in backgroundworker?

I am working on a WPF project where I have to import data from a lot of single files. 我正在一个WPF项目中,我必须从许多单个文件中导入数据。 The actual importing of those files and the data in them is being done in a backgroundworker doWork method. 这些文件及其中的数据的实际导入是通过backgroundworker doWork方法完成的。 It works like a charm, does the job and updating a progress bar also works perfectly. 它就像一个咒语,可以完成工作,并且更新进度条也可以完美地工作。

Now though, depending on what I encounter in those files, I occasionally need to get a decision from the User before I can proceed processing the current file. 现在,根据我在那些文件中遇到的情况,有时我需要从用户处获得一个决定,然后才能继续处理当前文件。

What is the best way to open a window/dialog, getting the values set in there back into the backgroundworker.doWork method and continue processing? 什么是打开窗口/对话框,将其中设置的值返回到backgroundworker.doWork方法并继续处理的最佳方法?

Is that even possible with a backgroundworker or do I need to keep that processing logic in the main/UI thread and update the progress bar from there somehow? 后台工作人员甚至可能做到这一点,还是我需要将该处理逻辑保留在main / UI线程中,并以某种方式从那里更新进度条?

I hope some of you can give me some hints or point me to other resources since I have not found much useful information for my specific problem. 我希望你们中的一些人能给我一些提示或指向其他资源,因为我没有找到有关我的特定问题的有用信息。

You can call the ShowDialog of an OpenFileDailog class on a new Thread or BackgroundWorker ( this will also create a new thread) 您可以在new ThreadBackgroundWorker上调用OpenFileDailog classShowDialog (这也会创建一个新的线程)

But when you want to pass or update any property or control that is running on the main thread you will need to use the Disptacher like this 但是,当您想要传递或更新在主线程上运行的任何属性或控件时,您将需要使用Disptacher如下所示

Dispatcher.BeginInvoke(new Action(() => { YourMethodThatUpdatesSomething(); }));

Background worker works in a different thread. 后台工作者在另一个线程中工作。 You can not invoke UI directly from a background thread. 您不能直接从后台线程调用UI。 One way of achiving what you are trying to do is by using a flag and Dispatcher to invoke UI for user input 实现您要执行的操作的一种方法是使用标志和分派器调用UI进行用户输入

    bool WaitFor_Input = false; //flag to indicate user input status

    private void ThreadRun()
    {
        //THIS IS IN Background worker thread
        //do task
        WaitFor_Input = true;
        //ask for user input
        Dispatcher.BeginInvoke(new Action(Show_Dialogue), null);
        while (WaitFor_Input); //Background worker waits untill user input is complete
        //continue further processing
    }

    private void Show_Dialogue()
    {
        //THIS IS IN UI THREAD
        //show your dialogue box here, update data variables
        //finally set
        WaitFor_Input = false;
    }

Keeping processing logic in a background thread is actually a good idea. 将处理逻辑保留在后台线程中实际上是一个好主意。

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

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