Wpf后台任务使用线程 [英] Wpf background task using thread

查看:113
本文介绍了Wpf后台任务使用线程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述





在我的应用程序中,我需要验证几条记录并且操作需要时间,因此我决定使用线程以保持UI响应。这是代码:



In my app I need to verify several records and the operation takes time, so I decided to use threads in order to keep the UI responsive. This is the code:

    string s = string.Empty;
    bool retValue = false;
    Thread _t = null;
    var aboutBox = new winWaitingMessage("Verifying");
    Action actVrfyDst = delegate
    {
        retValue = true;
        App.Current.Dispatcher.BeginInvoke(new Action(() => { aboutBox.Close(); }));
        if (_t != null && _t.IsAlive) _t.Abort();
    };
    ThreadStart strVrfyDst = delegate
    {
        App.Current.Dispatcher.BeginInvoke(new Action(() => { aboutBox.Show(); }));

        // Verify the data
        if (VerificaDistinta(out s))
            App.Current.Dispatcher.BeginInvoke(actVrfyDst);
        else
        {
            // End
            App.Current.Dispatcher.BeginInvoke(new Action(() => { aboutBox.Close(); }));
            if (_t != null && _t.IsAlive) _t.Abort();
        }
    };
    _t = new Thread(strVrfyDst);
    _t.SetApartmentState(ApartmentState.STA);
    _t.Start();






我可以申请或更改某些改进吗? />



Is there any improvement I may apply or change something?

推荐答案

以某种方式启动线程是做旧事情的旧方式。

Starting up threads in that sort of a way is the old way of doing stuff.

您应该使用任务< t>现在和异步等待。

You should use a Task<t> now and async await.

我建议你研究一下这种方法。

I recommend you look into that approach.

网上有很多关于这个的东西,但Stephen Cleary是异步等待的人。

There's a load of stuff about this out there on the web but Stephen Cleary is the go to guy for async await.

https://blog.stephencleary.com/2012/02/async-and-await.html

如果我按照你正在做的事情我会有一个异步显示aboutbox的方法。

If I follow what you're doing I'd have an async method which show the aboutbox.

等待异步任务。

这将返回你想要做的任何事情的结果。

That would return the result of whatever you're trying to do.

然后隐藏aboutbox。

Then hide the aboutbox.

如果您不希望用户在此期间执行任何其他操作,请在显示aboutbox时禁用该窗口。

Disable the window whilst showing aboutbox if you don't want the user to do anything else during that time.

如果我可以管理它,我宁愿不显示一个对话框,而是显示一条消息,我需要显示的内容是"正在进行"。

If I can manage it, I prefer not to show a dialog at all and instead to show a message and small spinner of I need to show something is "going on".

这是否合适取决于你的流程在做什么。

Whether that is appropriate here depends on what your process is doing.

我(也)不遵循为什么你这样做制作这个新线程apartmentstat.sta。

I (also) don't follow why you're making this new thread apartmentstat.sta.


这篇关于Wpf后台任务使用线程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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