1

I have async function which waits async Task<string>, but before that it should execute sync process(which is debug.log). However, instead main thread freezes until await return something.

Button's function which calls that async function

 private void Register()
    {
        LogRegHandler.logRegHandler.RegisterProcess(RegisterNamefield.text, RegisterEmailfield.text, RegisterPassfield.text)
;    

}

Async function which freeze main thread

public async void RegisterProcess(string name,string email, string password)
    {
        Debug.Log("before Await");
        RegLogUIController.regLogUIController.CreateLoadingPanel("dil controller editleyecek");
        string registerResult = await registerLogIn.RegisterUser(name,email, password);
        Debug.Log("after Await");
}

Awaited process

 public async Task<string> RegisterUser(string name, string email, string password)
    {
        string jsonResponse;
        try
        {
            var httpWebRequest = (HttpWebRequest)WebRequest.Create(serverAddress.serverMainAddress + "RegisterApi/register");
        httpWebRequest.ContentType = "application/json";
        httpWebRequest.Method = "POST";
        using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
        {

            string json = String.Format("{{\"name\":\"{0}\",\"email\":\"{1}\",\"password\":\"{2}\"}}",name,email,password);
            streamWriter.Write(json);
        }

        
            HttpWebResponse response = (HttpWebResponse)(await httpWebRequest.GetResponseAsync());
            StreamReader reader = new StreamReader(response.GetResponseStream());
            jsonResponse = reader.ReadToEnd();
        }
        catch (Exception)
        {
            return "";
        }
        return jsonResponse;

    }

log

before Await
after Await
//they pop-up at the same time after freezing ends

What I am doing wrong ?

Jsennin
  • 153
  • 2
  • 12
  • Try to run it as `Task.Run(() => LogRegHandler.logRegHandler.RegisterProcess(RegisterNamefield.text, RegisterEmailfield.text, RegisterPassfield.text));` In general why using `async void` instead of an `async Task` ? – derHugo Dec 16 '20 at 19:31
  • Also what speaks against using a [`UnityWebRequest.Post`](https://docs.unity3d.com/ScriptReference/Networking.UnityWebRequest.Post.html) in a Coroutine instead? – derHugo Dec 16 '20 at 19:32
  • I tried ```Task.Run(() => LogRegHandler.logRegHandler.RegisterProcess(RegisterNamefield.text, RegisterEmailfield.text, RegisterPassfield.text))``` , its log was only ```before Await```(after await does not pop up :( ).Also,tried same thing by changing async void to async Task, same result. ```registerLogIn.RegisterUser(name,email, password);``` registerLogin is non-monobehavior class that is why i cant use coroutine. – Jsennin Dec 17 '20 at 00:31
  • I would still use a Coroutine .. simply give it a MonoBehaviour reference that can and will be responsible for executing the Coroutine ;) – derHugo Dec 17 '20 at 06:52

1 Answers1

0

after tons of research I understand that error caused by this part

  var httpWebRequest = (HttpWebRequest)WebRequest.Create(serverAddress.serverMainAddress + "RegisterApi/register");

looks like it was sync process and freeze main thread .

to solve that you can follow this

How to use HttpWebRequest (.NET) asynchronously?

or use httpClient instead of HttpWebRequest

which I took as a reference here

https://blog.jayway.com/2012/03/13/httpclient-makes-get-and-post-very-simple/

so only awaited process changed

new awaited process

    public async Task<string> RegisterUser(string name, string email, string password)
    {

        string jsonResponse;
        string json = String.Format("{{\"name\":\"{0}\",\"email\":\"{1}\",\"password\":\"{2}\"}}", name, email, password);
        try
        {
            using (var client = new HttpClient())
            {
                HttpResponseMessage response = await client.PostAsync(serverAddress.serverMainAddress + "RegisterApi/register", new StringContent(json, Encoding.UTF8, "application/json"));
                response.EnsureSuccessStatusCode();
                jsonResponse = await response.Content.ReadAsStringAsync();

            }
               
            

        }
        catch (Exception)
        {
            return "";
        }
        return jsonResponse;

    }
Jsennin
  • 153
  • 2
  • 12