【问题标题】:How to start a bg thread on app startup in mvvm/wpf?如何在 mvvm/wpf 中的应用程序启动时启动 bg 线程?
【发布时间】:2014-09-13 10:32:31
【问题描述】:

在 wpf/mvvm 应用程序启动时启动后台线程的推荐方式是什么?也就是说,我想在 UI 初始化后立即启动一个线程。理想情况下,我想使用 xaml/command 来实现这一点。

谢谢。

【问题讨论】:

  • “理想情况下,我想使用 xaml/command 来实现这一点”。是什么阻止你这样做?
  • 我根本不知道该怎么做。也就是说,我不确定将标记代码放在哪里以及它应该是什么样子。非常感谢您提供建议或样本。
  • 不。把它放在app.xaml.cs的构造函数中就行了。并非所有内容都属于标记。

标签: wpf mvvm


【解决方案1】:

你想做什么?你确定你想要一个线程? 我假设您的程序将执行一些资源密集型操作,并且您希望 UI 保持响应。 如果您使用的是 .NET 4.x,请查看 Task Parallel Library。 如果您使用的是 .NET 5,请查看 async/await 模式。

这是我过去所做的: 在视图中:

<Button   ToolTip="Delete Selected Item" Command="{Binding DeleteItemCommand}"/>

在 ViewModel 中:

public DelegateCommand DeleteItemCommand { get; private set; }

(在 ViewModel 的构造函数中):

this.DeleteItemCommand = new DelegateCommand(this.DeleteItem, this.CanDeleteItem);

void DeleteItem()
{
    Task<int> task;
    try
    {
        task = Task.Run(() => YourTaskMethod(yourParameter));
        int result = task.Result;
    }
    catch(Exception ex)
}
static int YourTaskMethod(YourParameterType yourParameter)
{
    //do complex stuff
    return 1;
}

【讨论】:

  • 我确实需要一个在应用程序运行时运行的线程。它将负责查询数据库、检查文件时间戳、使用 REST 查询远程服务器等,并根据查询结果采取适当的措施。它的一些状态会被报告给 UI 线程。我可以在 app.xaml.cs 中以编程方式启动线程,但我想知道是否有办法在标记中执行此操作。
  • 听起来您在问一个广泛的高级问题。我仍然不认为你想要一个'线程'只是闲逛,等待被用来做你提到的所有事情。您可能最终会根据需要使用“任务”来执行这些操作。任务将隐藏实际的线程管理,这可能会很快变得棘手。希望这会有所帮助:blfoley.com/2012/06/26/…
  • 我认为我们在这里有点偏题了。可能有[更好的] 替代后台线程。但是,无论我使用什么技术,我仍然需要一种方法来在正确的时间以“MVVM”的方式在正确的位置启动操作。具体来说,我需要在 UI 初始化后立即从 XAML 触发操作。
【解决方案2】:

在浏览了这个网站上的各种文章后,我意识到要走的路是使用 EventTriggers。为了能够将触发器合并到我的应用程序中,我必须下载并安装 Expression Blend SDK。

这是一个适用于我的示例代码:

<Window x:Class="TestServer.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:i="clr-namespace:System.Windows.Interactivity;assembly=System.Windows.Interactivity"
        xmlns:ei="http://schemas.microsoft.com/expression/2010/interactions"  
        Title="MainWindow" Height="350" Width="525">

    <i:Interaction.Triggers>
        <i:EventTrigger EventName="Loaded">
            <!-- Execute a method called 'StartDaemon' defined in the view model -->
            <ei:CallMethodAction TargetObject="{Binding}" MethodName="StartDaemon"/>
        </i:EventTrigger>
        <i:EventTrigger EventName="Closing">
            <!-- Execute a method called 'StopDaemon' defined in the view model -->
            <ei:CallMethodAction TargetObject="{Binding}" MethodName="StopDaemon"/>
        </i:EventTrigger>
    </i:Interaction.Triggers>

    <Grid>
        <TextBlock Foreground="Red" Text="{Binding Path=DaemonText}" />
    </Grid>
</Window>

【讨论】:

    猜你喜欢
    • 2018-03-22
    • 1970-01-01
    • 1970-01-01
    • 2011-09-17
    • 1970-01-01
    • 2013-08-09
    • 2019-03-21
    • 1970-01-01
    • 2012-05-12
    相关资源
    最近更新 更多