非UI线程中的用户交互?

时间:2014-11-07 11:31:10

标签: c# multithreading user-interface backgroundworker

在我的WPF - C#应用程序中,我有一个耗时的功能,我用BackgroundWorker执行。此功能的作用是将文件中的给定数据添加到数据库中。偶尔,我需要一些用户反馈,例如数据已经存储在商店中,我想询问用户,他是想合并数据还是创建新对象或完全跳过数据。就像对话框窗口显示的那样,如果我尝试将文件复制到某个位置,那里已存在同名文件。

问题是,我无法从非GUI线程调用GUI窗口。我怎么能实现这种行为?

提前致谢,
弗兰克

4 个答案:

答案 0 :(得分:1)

您可以使用EventWaitHandle ou AutoResetEvent,然后每当您想要提示用户时,您都可以使用信号UI,然后等待响应。有关该文件的信息可以存储在变量中。

答案 1 :(得分:0)

如果可能......我的建议是将长期运行的任务构建为原子操作。然后,您可以创建一个可供后台线程和UI线程访问的项目队列。

public class WorkItem<T>
{
    public T Data { get; set; }
    public Func<bool> Validate { get; set; }
    public Func<T, bool> Action { get; set; }
}

你可以使用类这样的东西。它使用一个队列来管理工作项的执行,并使用一个可观察的集合来表示UI:

public class TaskRunner<T>
{
    private readonly Queue<WorkItem<T>> _queue;

    public ObservableCollection<WorkItem<T>> NeedsAttention { get; private set; }

    public bool WorkRemaining
    {
        get { return NeedsAttention.Count > 0 && _queue.Count > 0; }
    }

    public TaskRunner(IEnumerable<WorkItem<T>> items)
    {
        _queue = new Queue<WorkItem<T>>(items);
        NeedsAttention = new ObservableCollection<WorkItem<T>>();
    }

    public event EventHandler WorkCompleted;

    public void LongRunningTask()
    {
        while (WorkRemaining)
        {
            if (_queue.Any())
            {
                var workItem = _queue.Dequeue();

                if (workItem.Validate())
                {
                    workItem.Action(workItem.Data);
                }
                else
                {
                    NeedsAttention.Add(workItem);
                }
            }
            else
            {
                Thread.Sleep(500); // check if the queue has items every 500ms
            }
        }

        var completedEvent = WorkCompleted;
        if (completedEvent != null)
        {
            completedEvent(this, EventArgs.Empty);
        }
    }

    public void Queue(WorkItem<T> item)
    {
        // TODO remove the item from the NeedsAttention collection
        _queue.Enqueue(item);
    }
}

您的UI代码隐藏可能类似于

public class TaskRunnerPage : Page
{
    private TaskRunner<XElement> _taskrunner;

    public void DoWork()
    {
        var work = Enumerable.Empty<WorkItem<XElement>>(); // TODO create your workItems

        _taskrunner = new TaskRunner<XElement>(work);

        _taskrunner.NeedsAttention.CollectionChanged += OnItemNeedsAttention;

        Task.Run(() => _taskrunner.LongRunningTask()); // run this on a non-UI thread
    }

    private void OnItemNeedsAttention(object sender, NotifyCollectionChangedEventArgs e)
    {
        // e.NewItems contains items that need attention.
        foreach (var item in e.NewItems)
        {
            var workItem = (WorkItem<XElement>) item;
            // do something with workItem
            PromptUser();
        }
    }

    /// <summary>
    /// TODO Use this callback from your UI
    /// </summary>
    private void OnUserAction()
    {
        // TODO create a new workItem with your changed parameters
        var workItem = new WorkItem<XElement>();
        _taskrunner.Queue(workItem);
    }
}

此代码未经测试!但基本原则应该适合你。

答案 2 :(得分:0)

从这里的答案输入,我得到了以下解决方案:

(Mis)将Backgroundworker的ReportProgress方法与EventWaitHandle结合使用。如果我想与用户进行交互,我会调用ReportProgress方法并在等待时设置后台进程。在ReportProgress事件的Handler中,我进行了交互,完成后,我发布了EventWaitHandle。

    BackgroundWorker bgw;

    public MainWindow()
    {
        InitializeComponent();

        bgw = new BackgroundWorker();
        bgw.DoWork += new DoWorkEventHandler(bgw_DoWork);
        bgw.RunWorkerCompleted += new RunWorkerCompletedEventHandler(bgw_RunWorkerCompleted);
        bgw.WorkerReportsProgress = true;
        bgw.ProgressChanged += new ProgressChangedEventHandler(bgw_ProgressChanged);
    }

    // Starting the time consuming operation
    private void Button_Click(object sender, RoutedEventArgs e)
    {
        bgw.RunWorkerAsync();
    }

    // using the ProgressChanged-Handler to execute the user interaction
    void bgw_ProgressChanged(object sender, ProgressChangedEventArgs e)
    {
        UserStateData usd = e.UserState as UserStateData;

        // UserStateData.Message is used to see **who** called the method
        if (usd.Message == "X")
        {
            // do the user interaction here
            UserInteraction wnd = new UserInteraction();
            wnd.ShowDialog();

            // A global variable to carry the information and the EventWaitHandle
            Controller.instance.TWS.Message = wnd.TextBox_Message.Text;
            Controller.instance.TWS.Background.Set();
        }
    }

    void bgw_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
    {
        MessageBox.Show(e.Result.ToString());
    }

    // our time consuming operation
    void bgw_DoWork(object sender, DoWorkEventArgs e)
    {
        Thread.Sleep(2000);

        // need 4 userinteraction: raise the ReportProgress event and Wait
        bgw.ReportProgress(0, new UserStateData() { Message = "X", Data = "Test" });
        Controller.instance.TWS.Background.WaitOne();

        // The WaitHandle was released, the needed information should be written to global variable
        string first = Controller.instance.TWS.Message.ToString();

        // ... and again
        Thread.Sleep(2000);

        bgw.ReportProgress(0, new UserStateData() { Message = "X", Data = "Test" });
        Controller.instance.TWS.Background.WaitOne();

        e.Result = first + Controller.instance.TWS.Message;
    }

我希望我没有忽视一些关键问题。我对多线程并不那么熟悉 - 也许在某个地方应该有一些锁(对象)?

答案 3 :(得分:0)

特别针对您的情况

    private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
    {
        Thread.Sleep(1000);
        var a = Test1("a");
        Thread.Sleep(1000);
        var b = (string)Invoke(new Func<string>(() => Test2("b")));
        MessageBox.Show(a + b);
    }

    private string Test1(string text)
    {
        if (this.InvokeRequired)
            return (string)this.Invoke(new Func<string>(() => Test1(text)));
        else
        {
            MessageBox.Show(text);
            return "test1";
        }
    }

    private string Test2(string text)
    {
        MessageBox.Show(text);
        return "test2";
    }

Test2是一种常规方法,您必须从后台工作者调用Test1可以直接调用,并使用安全模式来调用自身。

MessageBox.Show类似于yourForm.ShowDialog(两者都是模态的),您将参数传递给它(text)并返回值(可以是{{1}的属性值当窗体关闭时设置。我使用的是yourForm,但它显然可以是任何数据类型。