c# - 等待抽象函数完成 c#

标签 c# asynchronous async-await task abstract

我有两个类(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 Taskawait 解决了这个问题,但我不确定这是否是最佳解决方案。如果我使用此解决方案,则在该任务完成之前几乎不会显示消息“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/

相关文章:

javascript - 了解 NodeJS 上的异步/等待

c# - Thread.Sleep(2500) 与 Task.Delay(2500).Wait()

c# - 简单实现 SHA-3 Keccak 散列到 C# 中的错误输出?

reactjs - 如何调度等待其他异步操作完成的 redux 操作?

c# - LINQ 组不工作

python - python 中的协程在 3.4 和 3.5 之间,如何保持向后兼容性?

c# - MVC5 异步操作结果。那可能吗?

mysql - 在 Node js es6 的异步函数中使用 for 循环时出现问题

c# - .NET 中是否有任何内置的稳定排序例程和交换函数?

c# - 缺少“管理私钥”选项