C#线程/异步:在后台运行一个任务,而UI是相互作用性 [英] C# Threading/Async: Running a task in the background while UI is interactable

查看:856
本文介绍了C#线程/异步:在后台运行一个任务,而UI是相互作用性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在两个异步/等待和线程四处寻找后,我仍然不能确定将它应用到我的情况的正确方法。不管,我尽我的用户界面的变化仍然挂起,因为我似乎并不被异步调用我想要的功能,另外,我可能实际上线程需要为我的解决方案。

After looking around on both Async/Await and Threading, I'm still unsure of the right way to apply it to my situation. No matter the variation that I try my UI still hangs because I don't seem to be calling my desired function asynchronously, additionally, I may in fact need threading for my solution.

我试图做的事:我有一个WPF应用程序上有一个按钮,我想通过UI或以其他方式启动的操作,仍然允许与程序的交互。一旦条件满足被该功能以外确定,该函数应该结束。对我来说,这听起来相当标准,但我有一种感觉,我误解的东西,我已经正确实现它。

What I'm trying to do: I have a WPF application on which there is a button that I would like to start an operation that still allows interaction with the program, through UI or otherwise. Once a condition is met that is determined outside of this function, the function should end. To me this sounds fairly standard but I have a feeling I'm misunderstanding something and I've implemented it incorrectly.

我有什么权利现在:

private async void start_button_Click(object sender, RoutedEventArgs e)
{
    await StaticClass.MyFunction();
}

private void stop_button_Click(object sender, RoutedEventArgs e)
{
    StaticClass.stopFlag = true;
}

public static Task<int> myFunction()
{
    //Stuff Happens

    while(StaticClass.stopFlag == false)
        //Do Stuff

    //Stuff Happens

    return Task.FromResult(1) //I know this is bad, part of the reason I'm asking
}

我希望就如果我处理这个正确的方式和我在做什么错的任何见解一些指导。

I was hoping for some guidance on if I'm approaching this the right way and any insight on what I'm doing wrong.

推荐答案

您已经肯定实现了它不正确。你返回任务&LT; INT方式&gt; ,但只的一旦所有的工作已经完成了

You've definitely implemented it incorrectly. You're returning a Task<int>, but only once all the work has already been done.

在我看来,你应该可能只是有一个的同步的方法:

It seems to me that you should probably just have a synchronous method:

private static void MyFunction()
{
    // Loop in here
}

然后开始一个任务是这样的:

Then start a task for it like this:

Task task = Task.Run((Action) MyFunction);

您可以再等待了任务,如果你想要的 - 尽管在这个例子中你已经给了,有这样做没有意义的,因为你没有在的await 反正。

You can then await that task if you want - although in the example you've given, there's no point in doing so, as you're not doing anything after the await anyway.

我也同意里德,使用一个的CancellationToken 会比静态标志别的地方清洁。

I'd also agree with Reed that using a CancellationToken would be cleaner than a static flag somewhere else.

这篇关于C#线程/异步:在后台运行一个任务,而UI是相互作用性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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