如何使用(委托方法)等待C#中的线程进程完成

时间:2013-12-18 06:21:18

标签: c# callback wait

请帮助我。我的想法是使用线程概念连续打印0到1000的数值。如果我的应用程序无异常关闭,我如何编写WAITING代码来完成当前正在运行的线程任务。

我提到示例代码......

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();
    }
}

1 个答案:

答案 0 :(得分:0)

如果您确定这是您需要做的,请尝试使用WaitHandle

AutoResetEvent _blocker = new AutoResetEvent(false);

//In background thread
_blocker.Set();

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