触发异步API调用的Windows窗体中的问题调用操作

时间:2019-03-16 18:09:49

标签: c# multithreading windows-forms-designer

我有一个控制台应用程序,它可以调用一个类并作为控制台应用程序运行或触发Windows窗体。 Windows窗体依次发送参数并调用其他相同的操作。

调用点:

  static void Main(string[] args)
    {
        if(AppSettingsHelper.GetValue<bool>("EnableWindowsForm"))
        {
            System.Console.WriteLine("EnableWindowsForm is set to true - Running Windows form");
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            //Application.Run(new Form1(0));

            //First Time
            var form = new ReportGeneratorForm();
            Application.Run(form);

        }
        else
        {
            System.Console.WriteLine("EnableWindowsForm is set to false - Running direct program in console");
            PortalMonitoring monitoring = new PortalMonitoring();
            monitoring.Process();
        }
    }

现在单击按钮会触发相同的类

 private void button1_Click(object sender, EventArgs e)
        {
    PortalMonitoring monitoring = new PortalMonitoring();
    monitoring.Process(DateTime.Now); //Date as paramater- Default is null
}

如果我触发控制台应用程序,它将运行良好。 但是,如果我单击按钮,代码将停留在异步Web api调用的位置-如下代码

int reportID = GetReportIDAsync().Result;



 private static async System.Threading.Tasks.Task<int> GetReportIDAsync()
        {
            var reportName = "Portal name";
            var reportID = await ops.GetReportId(reportName);

            LogAndWriteToConsole("Report ID Feched : " + reportID.ToString());
            return reportID;
        }

请在这里帮助我,我认为Windows窗体似乎不允许defauly多线程。该如何解决?

1 个答案:

答案 0 :(得分:1)

您没有显示从monitoring.Process()GetReportIDAsync()的完整路径,但是必须始终保持异步/等待状态。

顶层应如下所示:

private async void button1_Click(object sender, EventArgs e)
{
    // probably add a try/catch here
    PortalMonitoring monitoring = new PortalMonitoring();
    await monitoring.Process(DateTime.Now); //Date as paramater- Default is null
}

您的无Winforms分支应该使用monitoring.Process().Wait()