我正试图用C#的async/await/continuewith来玩.我的目标是必须有两个并行运行的任务,尽管哪个任务按顺序执行一系列操作.为此,我计划有一个List<Task>代表并行运行的2个(或更多)任务,并且ContinueWith在每个Task
问题上使用我的问题是,在await taskList已经返回的情况下,似乎不执行继续回调.
为了总结,这里有一个例子来说明我期待发生的事情:
class Program
{
static public async Task Test()
{
System.Console.WriteLine("Enter Test");
await Task.Delay(100);
System.Console.WriteLine("Leave Test");
}
static void Main(string[] args)
{
Test().ContinueWith(
async (task) =>
{
System.Console.WriteLine("Enter callback");
await Task.Delay(1000);
System.Console.WriteLine("Leave callback");
},
TaskContinuationOptions.AttachedToParent).Wait();
Console.WriteLine("Done with test");
}
}
Run Code Online (Sandbox Code Playgroud)
预期的产出是
Enter Test
Leave Test
Enter callback
Leave callback
Done with test
Run Code Online (Sandbox Code Playgroud)
但是,输出是
Enter Test
Leave Test
Enter callback
Done with test
Run Code Online (Sandbox Code Playgroud)
有没有办法让ContinueWith被调用的Task 等待提供的函数在被认为完成之前完成?即..Wait将等待两个任务完成,原始任务和ContinueWith返回的任务
信息:
"System.NotSupportedException was unhandled
Message: An unhandled exception of type 'System.NotSupportedException' occurred in mscorlib.dll
Additional information: A second operation started on this context before a previous asynchronous operation completed. Use 'await' to ensure that any asynchronous operations have completed before calling another method on this context. Any instance members are not guaranteed to be thread safe."
Run Code Online (Sandbox Code Playgroud)
码:
public async Task<IEnumerable<UserLangDTO>> ImportLang(int userId)
{
var userLangs = new List<UserLangDTO>();
using (FirstContext ctx = new FirstContext())
{
if (await (ctx.UserLang.AnyAsync(u => u.UserId …Run Code Online (Sandbox Code Playgroud)