2 回答

TA貢獻1772條經(jīng)驗 獲得超6個贊
回調(diào)函數(shù)本來就是在調(diào)用方的線程中被執(zhí)行的。
若真想在主線程中得到異步的結(jié)果,應(yīng)該用消息(SendMessage)而非回調(diào)。

TA貢獻1812條經(jīng)驗 獲得超5個贊
可以通過線程池ThreadPool來解決,使用ThreadPool.QueueUserWorkItem(回調(diào)函數(shù),object),將參數(shù)封裝在一個類的對象中,傳給回調(diào)函數(shù)去執(zhí)行。
TheadPool的用法:
1、創(chuàng)建一個ManualResetEvent的對象,就像一個信號燈,指示線程的掛起和執(zhí)行;
2、ManualResetEvent對象創(chuàng)建時,可以指定默認狀態(tài):true為有信號,false為無信號;
3、調(diào)用Reset()方法重置狀態(tài);
4、調(diào)用WaitOne()方法,使線程處于等待狀態(tài);
5、調(diào)用Set()方法設(shè)置狀態(tài)。
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;
using System.Collections;
namespace Demo
{
public class ParamObject
{
public int number;
public ParamObject (int number)
{
this.number = number;
}
}
public class ThreadClass
{
public Hashtable aHashTable;
public ManualResetEvent aManualResetEvent;
public static int iCount = 0;
public static int iMaxCount = 0;
public ThreadClass(int maxCount)
{
aHashTable = new Hashtable(maxCount);
iMaxCount = maxCount;
}
public void ThreadRun(object aParamObject)
{
Console.WriteLine("HashCode: {0}, Number in Object: {1}", Thread.CurrentThread.GetHashCode(), ((ParamObject)aParamObject).number);
lock (aHashTable)
{
if (!aHashTable.ContainsKey(Thread.CurrentThread.GetHashCode()))
{
aHashTable.Add(Thread.CurrentThread.GetHashCode(), 0);
}
aHashTable[Thread.CurrentThread.GetHashCode()] = (int)aHashTable[Thread.CurrentThread.GetHashCode()] + 1;
}
Thread.Sleep(3000);
Interlocked.Increment(ref iCount);
if (iCount == iMaxCount)
{
Console.WriteLine("Setting aManualResetEvent...");
aManualResetEvent.Set();
}
}
}
class Program
{
public static void Main(string[] args)
{
bool enableThreadPool = false;
int iMaxCount = 20;
ManualResetEvent aManualResetEvent = new ManualResetEvent(false);
Console.WriteLine("Insert {0} items to Thread Pool.", iMaxCount);
ThreadClass aThreadClass = new ThreadClass(iMaxCount);
aThreadClass.aManualResetEvent = aManualResetEvent;
// First, add an item to check if your system supports ThreadPool API function or not.
try
{
ThreadPool.QueueUserWorkItem(new WaitCallback(aThreadClass.ThreadRun), new ParamObject(0));
enableThreadPool = true;
}
catch (NotSupportedException ex)
{
Console.WriteLine("Thread Pool API is not supported in this system.");
enableThreadPool = false;
}
if (enableThreadPool)
{
for (int i = 1; i < iMaxCount; i++)
{
ThreadPool.QueueUserWorkItem(new WaitCallback(aThreadClass.ThreadRun), new ParamObject(i));
}
Console.WriteLine("Waiting for thread pool to drain");
aManualResetEvent.WaitOne(Timeout.Infinite, true);
Console.WriteLine("Thread Pool has been drained.");
Console.WriteLine("Load threads info:");
foreach (object key in aThreadClass.aHashTable.Keys)
{
Console.WriteLine("Key: {0}, Value: {1}", key, aThreadClass.aHashTable[key]);
}
}
Console.ReadLine();
}
}
}
- 2 回答
- 0 關(guān)注
- 131 瀏覽
添加回答
舉報