Skip to main content
 首页 » 编程设计

c#之从静态函数调用 InsertAsync 抛出 ThreadAbortException

2024年02月06日43kenshinobiy

我希望可能有一个简单的修复方法,但我看不到它。

我正在尝试从 C# 控制台程序将数据插入到 Azure 移动服务数据库中。但是,当程序从 VS 中运行时(通过 F5),在运行程序的常规过程中,数据不会被插入,也不会抛出异常(我可以看到)。当我将断点设置到 await dataModel.InsertAsync(data) 行并在立即窗口中运行它时,它会抛出 ThreadAbortException。感谢您的帮助。

Namespace TestApp { 
class Program 
{ 
    public static MobileServiceClient MobileService = new MobileServiceClient( 
    "https://x.azure-mobile.net/", 
    "API key"); 
 
    public static IMobileServiceTable<performance> dataModel = Program.MobileService.GetTable<performance>(); 
 
    static void Main(string[] args) 
    { 
        try 
        { 
            var test = new performance("http://www.example.com"); 
            var x = InsertItem(test); 
        } 
        catch (Exception ex) 
        { 
            System.Diagnostics.Debug.WriteLine(ex.StackTrace); 
        } 
    } 
static public async Task InsertItem(performance data) 
{ 
        await dataModel.InsertAsync(data).ConfigureAwait(false); 
} 
} 
 
class performance 
{ 
    [JsonProperty(PropertyName = "id")] 
    string Id { get; set; } 
    [JsonProperty(PropertyName = "uri")] 
    string Uri { get; set; } 
 
    public performance(string uri) 
    { 
        Uri = uri; 
    } 
 
} 
} 

请您参考如下方法:

您的问题来自于 var x = InsertItem(test); 是一个非阻塞调用。当您到达 await dataModel.InsertAsync(data).ConfigureAwait(false); 时,函数 InsertItem 立即返回一个 Task。

通常正确的方法是 await InsertItem(test); 但是因为您的代码是从 Main 调用的,所以您不能使函数 async 。因此,对于这个控制台应用程序(如果在 WinForms 或 WPF 应用程序中运行,这将不是正确的选择)您需要在结束之前放置一个 x.Wait() try-catch block 。

static void Main(string[] args) 
{ 
    try 
    { 
        var test = new performance("http://www.example.com"); 
        var x = InsertItem(test); 
 
        //This makes the program wait for the returned Task to complete before continuing. 
        x.Wait(); 
    } 
    catch (Exception ex) 
    { 
        System.Diagnostics.Debug.WriteLine(ex.StackTrace); 
    } 
} 

但是,如果您在 WPF 或 WinForms 应用程序中执行此操作,您只需将调用函数(假设该函数是一个事件)设为异步即可。

private async void Button1_OnClick(object sender, EventArgs e) 
{ 
    try 
    { 
        var test = new performance("http://www.example.com"); 
 
        //The code now waits here for the function to finish. 
        await InsertItem(test); 
    } 
    catch (Exception ex) 
    { 
        System.Diagnostics.Debug.WriteLine(ex.StackTrace); 
    } 
} 

不要执行async void 函数调用,除非您在事件委托(delegate)函数中