我需要为Task创建两个方法,每个方法都类似于ContinueWith(),但是会在主UI线程中执行contunuation。
带参数Action
,Action<Task>
方法返回Task(对于带Action的重载)。返回的任务必须在主要任务和继续之后完成 完成了。
Action
是否正确实现了功能?以及如何使用Action<Task> input
Returned task must finish only after main Task and continuation
的第二个案例
我实施了
namespace WpfApplication2
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private void Button_Click(object sender, RoutedEventArgs e)
{
TaskScheduler uiScheduler = TaskScheduler.FromCurrentSynchronizationContext();
WorkAsync WA = new WorkAsync();
Action firstaction = new Action(WA.Count);
WA.Work(firstaction, uiScheduler);
Action<Task> secondaction = new Action<Task>(); //What should be here?
WA.Work(secondaction, uiScheduler);
}
public class WorkAsync
{
public Task Work(Action input, TaskScheduler uiSchedule)
{
return Task.Factory.StartNew(input).ContinueWith((e) => { Console.WriteLine("Done"); }, uiSchedule);
}
public Task Work(Action<Task> input, TaskScheduler uiSchedule)
{
/// What should be here?
}
public void Count()
{
for (int i = 0; i < 10; i++)
{
System.Threading.Thread.Sleep(1000);
Console.WriteLine(i);
}
}
}
}
}
答案 0 :(得分:3)
您的要求听起来不对。
Action
的异步副本不是Action<Task>
- 它是Func<Task>
。框架中有许多方法可以支持我的上述陈述,Task.Run
是一个。
同样,对于Action<T>
,异步版本为Func<T, Task>
。对于Action<T1, T2>
,它是Func<T1, T2, Task>
。你明白了。
因此,考虑到这一点,您的实现现在变为:
public Task Work(Func<Task> input, TaskScheduler uiScheduler)
{
return input().ContinueWith(e => Console.WriteLine("Done"), uiScheduler);
}
这将允许这样的调用:
Task myCustomTaskFollowedByConsoleWriteLine = Work(async () =>
{
object result = await SomeIOWorkAsync();
SomeSynchronousCpuBoundWork(result);
},
uiScheduler);
现在,您甚至可以用Work(Func<Task>, TaskScheduler)
:
public Task Work(Action input, TaskScheduler uiScheduler)
{
return Work(() => Task.Run(input), uiScheduler);
}