等待抽象函数完成c#

时间:2015-06-28 04:17:26

标签: c# asynchronous async-await task abstract

我有两个类(CLASS1和CLASS2),来自CLASS1我调用一个抽象方法,我需要等到结束并显示消息“End Process ...”,我该如何解决这个问题?

CLASS-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);
}

CLASS-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”。

1 个答案:

答案 0 :(得分:4)

  

我需要等到结束并显示一条消息&#34;结束流程...&#34;,我该如何解决这个问题?

您将已执行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");
}