Wait for RunOnUIThread to finish and continue executing the rest of the task

Viewed 2718

im developing an app for android via c#(xamarin.visual studio) , the problem is that i have some task to do that running in other threads , and when it should update the layout it should call Activity.RunOnUIThread , everything it's working well but the thread dont wait this method to finnish and continue executing the rest withuout waiting.

The question is : How to wait for RunOnUIThread to finish and after that continue executing rest of the commands of the task. ?

public void start(int threadCounter)
    {
        for (int i = 0; i < threadCounter; i++)
        {

            Thread thread1 = new Thread(new ThreadStart(RunScanTcp));
            thread1.Start();

        }

    }
    public void RunScanTcp()
    {

        int port;

        //while there are more ports to scan 
        while ((port = portList.NextPort()) != -1)
        {
            count = port;

            Thread.Sleep(1000); //lets be a good citizen to the cpu

            Console.WriteLine("Current Port Count : " + count.ToString());

            try
            {

                Connect(host, port, tcpTimeout);

            }
            catch
            {
                continue;
            }

            Activity.RunOnUiThread(() =>
            {
                mdata.Add(new data() { titulli = "Port : " + port, sekuenca = "Sequence : ", ttl = "Connection Sucessfull !", madhesia = "", koha = "Time : " });
                mAdapter.NotifyItemInserted(mdata.Count() - 1);
                if (ndaluar == false)
                {
                    mRecyclerView.ScrollToPosition(mdata.Count() - 1);
                }
            }); // in that point i want to wait this to finish and than continue below...
            Console.WriteLine("TCP Port {0} is open ", port);

        }
3 Answers

For those interested in an async/await solution, there is Stephen Cleary's AsyncManualResetEvent, e.g.:

var mre = new AsyncManualResetEvent();
this.context.RunOnUiThread(() =>
{
    // Do awesome UI stuff
    mre.Set();
});
await mre.WaitAsync();
Related