2

我想在下面实现一些生活 -

在此处输入图像描述

我的应用程序将启动 UI 模块,从 UI 模块我将启动核心模块。核心模块将继续在不同的线程上运行。在核心模块中的特定操作上,我想引发 UI 模块订阅的事件。

基本上,我想将特定的枚举信息发送到 UI 模块。

请给我推荐一个模型。我正在努力实现它。

在这个模型中,这两个模块都会在任何阻塞的情况下运行吗?

提前致谢

4

4 回答 4

1

I would recommend using the BackgroundWorker Class

Checkout this tutorial http://www.dotnetperls.com/backgroundworker

Class reference http://msdn.microsoft.com/en-us/library/system.componentmodel.backgroundworker.aspx

Here how it goes in simple ways:

  1. Open your UI form (design view)
  2. Add a backgroundworker control on your UI form
  3. Open the properties pane and switch to events (lightning bolt icon)
  4. Double click on dowork and runworkercompleted events (this will generate event handlers)
  5. Go to the event handlers (in code)
  6. Now write your processing code in dowork handler and add the result you want to send to your ui module like so e.Result = your_enum (or any other Object);
  7. Next come to the runworkercompleted handler and typecast the RunWorkerCompletedEventArgs e (RunWorkerCompletedEventArgs object) to your enum (or object you returned from the dowork handler) and use it in UI as needed.
  8. Finally do not forget to initiate the backgroundworker : backgroundWorker1.RunWorkerAsync() from your UI mdoule

Remark: If you need to report progress periodically use the ReportProgress method of BackgroundWorker class. There are two overloads for this method: 1) http://msdn.microsoft.com/en-us/library/ka89zff4.aspx 2) http://msdn.microsoft.com/en-us/library/a3zbdb1t.aspx

The first one allows to report only the progress percentage and the second one you can use to pass in any object also if you will

于 2013-02-06T18:33:52.647 回答
1

您可以使用Progress带有IProgress接口的类来执行此操作。

  1. 在您的 UI 上下文中Progress,使用您需要传递的任何数据的通用参数创建一个对象。

  2. 当后台任务更新您时,订阅它的事件以执行您想做的任何事情。

  3. 让后台任务接受一个类型的对象IProgressProgress实现)并定期让它Report与相关数据一起使用。

每当调用该ProgressChanged事件时都会触发该事件,并且该对象将捕获其创建位置的当前同步上下文,这是一种奇特的说法,即该事件将在 UI 线程中触发。ReportProgress

于 2013-02-06T17:25:48.863 回答
0

对我来说,这听起来像是中介者模式的经典用法。Mediator 允许断开连接的组件相互通信。

我只是碰巧在我自己的 MVVM 框架中有一个副本,你可以从这里获取:

http://cinch.codeplex.com/SourceControl/changeset/view/70832#796984

也抢这个

http://cinch.codeplex.com/SourceControl/changeset/view/70832#797008

我的实现允许您使用 Wea​​kReference 来执行此操作,因此不会保留强引用。它还允许订阅者使用属性连接方法来监听某些事件,并允许发布者广播 T 的新消息。

发布者/订阅者只需向 Mediator 注册

//done by both subscriber and publisher
Mediator.Instance.Register(this);


//Subscriber
[MediatorMessageSinkAttribute("DoBackgroundCheck")]
void OnBackgroundCheck(string someValue) { ... }


//publisher might typically do this
mediator.NotifyColleagues("DoBackgroundCheck", "Nice message");

当订阅者收到消息(WPF / Winforms 已经预先构建了这些消息)时,您可能需要使用自己的SynchronizationContext来将调用调度到正确的线程。

我还允许同步/aysynchronise 调用

于 2013-02-06T17:24:39.870 回答
0

System.Threading.Thread使用or BackgroundWorkerorTask类应该很容易做到这一点。您可以使用其中任何一个在另一个线程上运行代码。

当您需要通知 UI 时,只需引发一个事件。要构建事件,请看这里:

如何在 C# 中创建自己的事件?

然后您只需要确保调用Invoke以确保您在正确的线程上执行最终的 UI 更新代码。为此,请看一下:

线程控制.调用

于 2013-02-06T17:18:24.110 回答