C#需要等待线程完成而不阻塞UI线程

问题描述 投票:0回答:2

我在UI线程上显示ProgressBar,然后在另一个线程上启动登录过程。这完美无缺,我得到ProgressBar“圈子”,让用户知道正在发生的事情。问题是我需要通过UI向用户返回任何登录错误,例如无效的用户名/密码。我将ProgressBar类更改为包含ErrorMessage属性,将其实例化并将其作为参数传递给登录过程。在任何错误我设置ErrorMessage属性。如果它不为null,我显示错误。问题是登录线程在我到达检查null的if之前没有完成。这一切都是在按钮点击事件中完成的。我的代码:

MyButton_Submit.Click += async (sender, e) =>
{
        ManualResetEvent resetEvent = new ManualResetEvent(false);
        ProgressBarHandler myprogressbar = new ProgressBarHandler(this);
        myprogressbar.show();

        var thread = new System.Threading.Thread(new ThreadStart(async delegate
        {
            await SignOn(myprogressbar);
            resetEvent.Set();
        }));
        thread.Start();
        // based on @Giorgi Chkhikvadze comment below I changed: resetEvent.WaitOne(); to:

        await Task.Run(() => resetEvent.WaitOne());
        // works perfectly 


        while (thread.ThreadState == ThreadState.Running)
        {
            await Task.Delay(100);
        }
        myprogressbar.hide();

        if (myprogressbar.ErrorMesage != null)
        {
            Context context = Application.Context;
            string text = myprogressbar.ErrorMesage ;
            ToastLength duration = ToastLength.Short;
            var toast = Toast.MakeText(context, text, duration);
            toast.Show();
        }
    };
}

resetEvent.WaitOne();显然阻止了UI,因为当我将其注释掉时,会显示进度条,当我执行它时,它不会。我怎样才能解决这个问题?

*编辑 - 添加了SignOn代码*

    private async Task SignOn(ProgressBarHandler MyProgress)
    {
        Boolean error = false;

        // Hide the keyboard ...
        InputMethodManager imm = (InputMethodManager)GetSystemService(Context.InputMethodService);
        imm.HideSoftInputFromWindow(aTextboxPassword.WindowToken, 0);

        // Check permissions
        var mypermission = ApplicationContext.CheckCallingOrSelfPermission(Android.Manifest.Permission.Internet);

        if (ApplicationContext.CheckCallingOrSelfPermission(Android.Manifest.Permission.Internet) != Android.Content.PM.Permission.Granted)
        {

            int MY_REQUEST_CODE = 0;
            //int x = 0;
            RequestPermissions(new String[] { Android.Manifest.Permission.Internet },
                    MY_REQUEST_CODE);
            //x = 1;
        }

        mypermission = ApplicationContext.CheckCallingOrSelfPermission(Android.Manifest.Permission.Internet);

        if (ApplicationContext.CheckCallingOrSelfPermission(Android.Manifest.Permission.AccessNetworkState) != Android.Content.PM.Permission.Granted)
        {

            int MY_REQUEST_CODE = 0;
            RequestPermissions(new String[] { Android.Manifest.Permission.AccessNetworkState },
                    MY_REQUEST_CODE);
        }

        MyUser.Username = aTextboxUsername.Text.Trim();
        MyUser.Password = aTextboxPassword.Text.Trim();
        try
        {

            ConnectivityManager connectivityManager = (ConnectivityManager)GetSystemService(ConnectivityService);

            NetworkInfo activeConnection = connectivityManager.ActiveNetworkInfo;
            bool isOnline = (activeConnection != null) && activeConnection.IsConnected;

            if (isOnline)
            {
                ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
                OMLDataInterfaceWeb.OMLDataInterface myService = new OMLDataInterfaceWeb.DataInterface();

                try
                {
                    result = myService.Logon(MyUser.Username, MyUser.Password);

                }
                catch (Exception ex)
                {
                    MyProgress.ErrorMesage = "Logon attempt failed due to error: " + ex.Message;
                }
            }
            else
            {
                MyProgress.ErrorMesage = "There is no internet connection or cell phone connection.  Connect to a network or connect to a cellular network.";
            };
        }
        catch (Exception ex)
        {
            MyProgress.ErrorMesage = "Connectivity Manager failed to create a connection due to error: " + ex.Message;
        };

        if (result == "CONNECTED")
        {
            PopulateMyUser();
            StoreUsernamePassword();


            var usertype = MyUser.Usertype.ToUpper();
            if (usertype == "ADMIN")
            {
                Intent intent = new Intent(this, typeof(Drawer));
                Bundle bundlee = new Bundle();
                bundlee.PutParcelable("MyUser", MyUser); // Persist user class to next activity
                intent.PutExtra("TheBundle", bundlee);
                StartActivity(intent);
            }

        }
        else
        {
            try
            {
                error = true;
                errormsg = "Logon Error: Invalid Username or Password.";
            }
            catch (Exception ex)
            {
                MyProgress.ErrorMesage = "An error occured while attempting to set the error message, the error is: " + ex.Message;
            }
        };
        try
        {
            if (error)
            {
                MyProgress.ErrorMesage = "An error occured during the logon process (2), The error is: " + errormsg;
            }
        }
        catch (Exception ex)
        {
            MyProgress.ErrorMesage = "An error occured during the logon process (2), The error is: " + ex.Message;
        }
    }

*注意:*发布此代码后,我发现我需要使用权限进行更多工作,权限对话框不太可能出现在此线程上的用户,因此我需要将其移出此过程。

c# xamarin.android
2个回答
0
投票

等待Task.Run(() => resetEvent.WaitOne());应该做的伎俩。 ManualResetEvent不是等待的,不能直接使用await关键字,所以你需要将它包装在任务中


1
投票

你不需要一个单独的线程; await将自行工作。你也不需要ManualResetEvent作为工作完成的“信号”;在await上使用Task可以正常工作。

等效的简化代码:

MyButton_Submit.Click += async (sender, e) =>
{
  ProgressBarHandler myprogressbar = new ProgressBarHandler(this);
  myprogressbar.show();

  await SignOn(myprogressbar);
  myprogressbar.hide();

  if (myprogressbar.ErrorMesage != null)
  {
    ...
  }
};

你永远不应该在Xamarin应用程序中输入Thread。总有一种更简单,更好的方法。 Thread类型一般是“强黄色”旗帜,但在Xamarin中是一面红旗。

© www.soinside.com 2019 - 2024. All rights reserved.