【问题标题】:Some C# code cause to "Server Busy" error message一些 C# 代码导致“服务器忙”错误消息
【发布时间】:2020-08-18 15:59:18
【问题描述】:

以下代码:

(调用返回Task的异步方法)

...
        Task<int> taskInt = Globals.ThisAddIn._DAL.InsertTestAceQL();
        int resInt = taskInt.Result;
        MessageBox.Show("resInt= " + resInt.ToString());
...
        public async Task<int> InsertTestAceQL()
        {
            int res = int.MinValue;
            try
            {
                string sql = "INSERT INTO dbo.AceQLTst2 VALUES ('From Visio')";

                AceQLCommand command = new AceQLCommand(sql, AceQLConn().Result);
                try
                {
                    res = await command.ExecuteNonQueryAsync();
                }
                catch (AceQLException ex)
                {
                    Globals.ThisAddIn.HandleException(ex.Message);
                }
            }
            catch (Exception ex)
            {
                Globals.ThisAddIn.HandleException(ex.Message);
            }

            return res;
        }
...

导致以下错误信息:

代码卡住了。

有人知道吗?

【问题讨论】:

  • 尝试重新启动服务器并再次运行代码。
  • .Result 是访问异步操作结果的错误方法。其中之一是导致死锁。
  • @Arsen,没用。顺便说一句,相同的代码在“控制台应用程序”中运行良好,但在“类库”Visio 加载项中运行不佳。
  • @GalTzemach,抱歉,消息“...busy”让我认为应用程序挂起可能是主要原因。您与 DB 的测试连接是否按预期工作?您是否还尝试输入一些真正的整数而不是int.MinValue?您是否能够通过查询从数据库中获取一些值,或者仅插入失败?尝试回答这些问题,希望对您有所帮助。
  • “只有当我在 UI 线程工作期间尝试此操作时才会出现错误消息” -- 这是一个 非常 不同的上下文,而这种差异是导致的问题。关键是你需要做正确的awaits 才能得到结果。如果您不在async-marked 方法中,则需要进行一些研究。调用.GetAwaiter().GetResult() 仍可能导致死锁,具体取决于线程上安排的其他内容。通过Stephen Cleary阅读所有关于异步的内容。

标签: c# .net async-await task vsto


【解决方案1】:

没有 C# 代码导致任何服务器繁忙。

发生的情况是 UI 被此代码阻止:

int resInt = taskInt.Result;

并且 Windows 告诉您应用程序正忙并且没有响应 - 阻止 UI。

【讨论】:

  • 谢谢。那么,从非异步(常规)方法调用和等待异步方法结果的正确方法是什么?
  • async 方法和await 中。 InsertTestAceQL 中的 al awaits 应该有 ConfigureAwait(false)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-01-01
  • 2021-04-16
  • 2013-11-28
  • 2022-10-22
  • 1970-01-01
相关资源
最近更新 更多