简体   繁体   中英

How to wait until thread process finishes in C# using (Delegate Method)

Kindly help me. My idea is to continually print Numeric values form 0 to 1000 using thread concept. In case unexceptionally my application closes, how can I write the code WAITING for currently running thread tasks to complete.

Here by i mention sample code...

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Threading;
using System.Runtime.Remoting.Messaging;
using System.IO;

namespace Test_AsyncFactorCaller
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        public bool Work()
        {
            int nSleep = 100;
            WriteMessage(string.Format("Going to Thread Sleep State for {0} sec", nSleep));
            for (int i = 0; i < nSleep; i++)
            {
                WriteMessage(string.Format("Sleeping = {0}", i));
                Thread.Sleep(1000);
            }
            WriteMessage("Going to Thread Wakeup State");
            return true;
        }
        public void Work_Done(IAsyncResult result)
        {
            WriteMessage("Work_Done");
            AsyncFactorCaller t = (AsyncFactorCaller)((AsyncResult)result).AsyncDelegate;
            bool bResult = t.EndInvoke(result);
            WriteMessage(string.Format("Result {0}",bResult));
            result.AsyncWaitHandle.Close();
        }
        public void WriteMessage(string sMessage)
        {
                using (StreamWriter sw = new StreamWriter(@"C:\ThreadLog.txt", true))
                {
                    sw.WriteLine(sMessage);
                    sw.Close();
                }
        }
        private void btn_asyncCaller_Click(object sender, EventArgs e)
        {
            try
            {
                AsyncFactorCaller dGate_caller = new AsyncFactorCaller(Work);
                AsyncCallback Completed_callBack = new AsyncCallback(Work_Done);
                AsyncOperation asyncOperation = AsyncOperationManager.CreateOperation(null);
               IAsyncResult result = dGate_caller.BeginInvoke(Completed_callBack, "Test thread");
             }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message.ToString());
            }
        }
       public delegate bool AsyncFactorCaller();
    }
}

If you are really sure that this is what you need to do, try using a WaitHandle .

AutoResetEvent _blocker = new AutoResetEvent(false);

//In background thread
_blocker.Set();

//Where you want to wait for it
_blocker.WaitOne();

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