我有两个类(CLASS1 和 CLASS2),我从 CLASS1 调用一个抽象方法,我需要等待它结束并显示消息“结束进程...”,我该如何解决这个问题?
1 级:
public abstract partial class CLASS1 : Form
{
public CLASS1()
{
Console.WriteLine("Start Process ABSMethod1");
ABSMethod1("var1", "var2");
Console.WriteLine("End Process ABSMethod1");
Console.WriteLine("Start Process ABSMethod2");
ABSMethod2(1, 2);
Console.WriteLine("End Process ABSMethod2");
}
protected abstract void ABSMethod1(String var1, String var2);
protected abstract void ABSMethod2(int var1, int var2);
}
2 级:
class CLASS2: CLASS1
{
protected override void ABSMethod1(String var1, String var2)
{
if (var1 == "test")
{
Task.Factory.StartNew(() =>
{
Parallel.ForEach<clssmt>(items, item =>
{
/* ... */
});
});
}
//if i use Task.Wait() freezes UI.
}
protected override void ABSMethod2(int var1, int var2)
{
Task.Factory.StartNew(() =>
{
Parallel.ForEach<clssmt>(items, item =>
{
/* ... */
});
});
}
}
我使用 protected virtual async Task
和 await
解决了这个问题,但我不确定这是否是最佳解决方案。如果我使用此解决方案,则在该任务完成之前几乎不会显示消息“End Procces”。
最佳答案
i need wait to end of it and show a message "End Process...", how can i solve this?
您将那些已执行的Task
公开给调用者。您也不通过构造函数调用它们,而是通过初始化方法:
protected abstract Task FirstMethodAsync(string var1, string var2);
protected abstract Task SecondMethodAsync(int var1, int var2);
public async Task InitializeAsync()
{
Console.WriteLine("Start Process ABSMethod1");
await FirstMethodAsync("var1", "var2");
Console.WriteLine("End Process ABSMethod1");
Console.WriteLine("Start Process ABSMethod2");
await SecondMethodAsync(1, 2);
Console.WriteLine("End Process ABSMethod2");
}
关于c# - 等待抽象函数完成 c#,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31096103/