簡體   English   中英

如何使用(Delegate方法)等待直到線程處理在C#中完成

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

請幫助我。 我的想法是使用線程概念從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();
    }
}

如果您確實確定這是您需要做的,請嘗試使用WaitHandle

AutoResetEvent _blocker = new AutoResetEvent(false);

//In background thread
_blocker.Set();

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM