异步命令Wpf C#

时间:2018-07-25 11:43:34

标签: c# wpf asynchronous

程序具有一个更新按钮,该按钮将请求发送到服务器。我的任务是,当您单击该按钮时,将在单独的异步线程中启动对服务器的请求,并且在用户界面(wpf)上会出现图像“ spinner-loading”。我收到一个错误:

  

“无法将lambda表达式转换为预期的委托类型,因为该块中的某些返回类型不能隐式转换为委托的返回类型”。

如何结合使用asyncvoid,或者我可以做点更好的事情吗?

ViewModel:

public CarasViewModel()
    {
      ...
     AddCommand = new AsyncCommand<Task>(() => Add());
      ...
    }

public IAsyncCommand AddCommand { get; private set; }
    async Task Add()
    {
        await Task.Run(() => OnAdd());
    }

void OnAdd()
    {
        var Result = Helper.Get(Configuration.Settings);
        if (Result != null)
        {
            var SelectionViewModel = new SelectionViewModel(Result);
            if (DialogService.ShowModalWindow(selectionViewModel))
            {
                ...
            }
        }
        else
        {
            MessageBoxService.ShowError("Check your connection settings.");
        }
    }

代码段AsyncCommand:

public class AsyncCommand<TResult> : AsyncCommandBase, INotifyPropertyChanged
{
    private readonly Func<Task<TResult>> _command;
    private NotifyTaskCompletion<TResult> _execution;

    public AsyncCommand(Func<Task<TResult>> command)
    {
        _command = command;
    }
...

2 个答案:

答案 0 :(得分:-1)

您对TResult和Task感到困惑。 由于您已经AsyncCommand<TResult>

public class AsyncCommand<TResult> : AsyncCommandBase, INotifyPropertyChanged
{
}

静态AsyncCommand类,类似于创建命令的工厂

    public static class AsyncCommand
    {
        public static AsyncCommand<object> Create(Func<Task> command)
        {
            return new AsyncCommand<object>(async () => { await command(); return null; });
        }

        public static AsyncCommand<TResult> Create<TResult>(Func<Task<TResult>> command)
        {
            return new AsyncCommand<TResult>(command);
        }
    }

接下来,您由工厂AsyncCommand创建命令,如下所示:

public async Task<string> Add()
{
    //you can put whatever you want, in my project, it's string containing the message
    //your stuff
    var Result = Helper.Get(Configuration.Settings);
}

private AsyncCommand<string> _addCommand;
public AsyncCommand<string> AddCommand
        {
            get
            {
                if (_addCommand!= null)
                    return _addCommand;

                _addCommand= AsyncCommand.Create(Add);
                return _addCommand;
            }
        }

XAML

如果任务正在执行,我会显示进度条

<Grid VerticalAlignment="Center" Visibility="{Binding AddCommand.Execution, Converter={StaticResource NullToVisibilityConverter}}">
                <!--Busy indicator-->
                <ProgressBar HorizontalAlignment="Stretch" Foreground="{Binding AccentBaseColor}" 
                                           Visibility="{Binding AddCommand.Execution.IsNotCompleted,
                             Converter={StaticResource BooleanToVisibilityConverter}}"
                             IsIndeterminate="True"
                             Value="100" />
</Grid>

答案 1 :(得分:-2)

我们认为这可能是语义模型错误。语义模型应为所有lambda表达式都显示null类型。

您应该在调用命令时使用调度程序。

public CarasViewModel()
{
 AddCommand = new ICommand<Task>(() => Add());
}

public ICommand AddCommand { get; private set; }

async Task Add()
{
   Thread longRunningThread = new Thread(new ThreadStart(delegate (){ Thread.Sleep(10000); Application.Current.Dispatcher.BeginInvoke(System.Windows.Threading.DispatcherPriority.Normal, new CalculateTimeElapsed(OnAdd)); }));
longRunningThread.Start();}
void OnAdd{}