简体   繁体   English

C#在线程内部调用异步方法

[英]C# Call async method inside thread

Maybe I did not search correctly here in the forum because I did not find a similar problem. 也许我没有在论坛中正确搜索,因为我没有发现类似的问题。
Well, my problem is when I try to execute an async method inside a thread . 好吧,我的问题是当我尝试在thread内执行async方法时。

When I run the method (Register) without the thread it works perfectly! 当我在没有thread情况下运行方法(Register) ,它可以完美运行! Below is an example of the scenario. 下面是该方案的示例。

private SyncProcess _sync = new SyncProcess();
private static HttpClient _httpClient = new HttpClient();
private Thread _thread;

public class SyncProcess : ISyncProcess
{
    public event CompleteHandler OnComplete = delegate { };
    // another properties ...

    public void Run()
    {
        // import rules
        // ...
        OnComplete();
    }
}

public void TestImport()
{
    Register(idsync, "start"); // here register works fine
    _sync.OnComplete += ImportComplete;
    _thread = new Thread(() =>
    {
        try
        {
            _sync.Run();
        }
        catch (Exception ex)
        {
            // not fall here
        }
    });
    //
    _thread.Start();
}

private void ImportComplete()
{
    // other end-of-import rules
    // ...
    Register(idsync, "complete");  // here register not works
}

public async Task<string> Register(int idsync, string type)
{
    string url = "myurl";
    var stringContent = new FormUrlEncodedContent(new[] { new KeyValuePair<string, string>("json", "myjson") }); 
    var response = await _httpClient.PostAsync(url + type, stringContent);
    if (response.IsSuccessStatusCode)
    {
        // do something
    }
    return "";
}

The problem occurs when I call the method (Register) inside the thread, another thing is that is that it does not generate error does not fall into the try , the debugging simply terminates. 当我在线程内调用方法(Register)时会发生问题,另一件事是它不会产生错误,不会掉入try ,调试只会终止。 I've tried adding try code everywhere but never crashed in catch . 我已经尝试添加try代码随处可见,但从来没有坠毁catch
Debug always aborts on the following line: 调试总是在以下行中止:

var response = await _httpClient.PostAsync(url + type, stringContent);


What should I do in this case? 在这种情况下我该怎么办?

Updated the code returning string in the Register method, but the same error remains. 更新了Register方法中的代码返回字符串,但是仍然存在相同的错误。
Thanks any suggestions! 谢谢任何建议!

Your problem is due to the use of async void , which should be avoided . 您的问题是由于使用了async void应避免使用 One of its problems is that you can't catch exceptions using try / catch . 它的问题之一是您不能使用try / catch捕获异常。

Event handlers in C# are a "fire-and-forget" kind of language feature. C#中的事件处理程序是一种“一劳永逸”的语言功能。 In particular, asynchronous event handlers must use async void , and this means the event-publishing code cannot see those exceptions. 特别是,异步事件处理程序必须使用async void ,这意味着事件发布代码无法看到这些异常。 If you want to allow async event handlers and handle exceptions (or other results) from them, you can use a "deferral" solution or make your event handler delegate return Task instead. 如果要允许async事件处理程序并处理它们的异常(或其他结果),则可以使用“延迟”解决方案,或者使事件处理程序委托返回Task

Async void will not allow you to catch any exceptions and will terminate your application when one is thrown. 异步void不允许您捕获任何异常,并且在引发异常时将终止您的应用程序。 Exceptions are only observed and handled as normal exceptions when using task instead of void. 仅在使用task而不是void时才观察到异常并将其作为普通异常处理。

You can read all about it here link 您可以在这里阅读所有相关链接

I can not answer your first question on why it works without the thread without more information. 我无法回答您的第一个问题,即如果没有更多信息,没有线程为什么它可以工作。 I can guarantee you thought that it has nothing to do with multi threading as far as I know since the main thread is also just a thread like any other. 我可以保证,就我所知,它与多线程无关,因为主线程也只是任何其他线程。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM