简体   繁体   中英

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 .

When I run the method (Register) without the thread it works perfectly! 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. I've tried adding try code everywhere but never crashed in 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.
Thanks any suggestions!

Your problem is due to the use of async void , which should be avoided . One of its problems is that you can't catch exceptions using try / catch .

Event handlers in C# are a "fire-and-forget" kind of language feature. In particular, asynchronous event handlers must use async void , and this means the event-publishing code cannot see those exceptions. 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 void will not allow you to catch any exceptions and will terminate your application when one is thrown. Exceptions are only observed and handled as normal exceptions when using task instead of 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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