它是這個問題的後續。使用線程池
https://stackoverflow.com/questions/12260170/how-to-make-a-threadpool-to-be-nonblocking
我一直在使用接口來實現它。我已經使用操作/刪除&使用接口非阻塞。是否有任何其他方式在.net中,我可以使下面的一段代碼nonblocking?接口實現如下。在任何時間點,我應該只有三個功能主,FuncA & FuncB
如果有人可以提供幫助。它會非常感激。謝謝。
using System;
using System.Threading;
namespace ConsoleApplication2
{
public interface IOperation
{
void CallBack(int i);
}
public class FuncBCalculation
{
public int N { get { return _n; } }
private int _n;
public int MyValue { get; set; }
public FuncBCalculation(int n)
{
_n = n;
}
// Wrapper method for use with thread pool.
public void FuncB(object context)
{
IOperation FuncBcallback = (IOperation)context;
Thread.Sleep(5);
MyValue = _n + 2;
FuncBcallback.CallBack(MyValue);
}
}
public class ActualClass : IOperation
{
int Finalvalue = 0;
public static IOperation MainThreadCallBack { get; set; }
public void FuncA(int input, int i, IOperation callback)
{
input += 1;
var f = new FuncBCalculation(input);
MainThreadCallBack = callback;
IOperation op = new ActualClass();
ThreadPool.QueueUserWorkItem(f.FuncB, op);
}
//Method for callback operation
public void CallBack(int i)
{
Finalvalue = i + 3;
if (MainThreadCallBack != null)
MainThreadCallBack.CallBack(Finalvalue);
}
}
public class ThreadPoolExample : IOperation
{
static void Main()
{
ActualClass actualCall;
const int TotalLoopCount = 1000;
int input = 11;
Console.WriteLine("launching {0} tasks...", TotalLoopCount);
for (int i = 0; i < TotalLoopCount; i++)
{
IOperation op = new ThreadPoolExample();
actualCall = new ActualClass();
actualCall.FuncA(input, i, op);
}
Console.ReadKey();
}
//Method for callback operation for the main thread
public void CallBack(int i)
{
Console.WriteLine("The final Result is {0}", i);
}
}
}
你還必須定義'非阻塞'。並嘗試提供一個有些現實的用例和/或描述。以前因爲很好的理由而關閉。請注意,改進後可重新打開。 –
可能重複[如何使一個線程池是非阻塞?](http://stackoverflow.com/questions/12260170/how-to-make-a-threadpool-to-be-nonblocking) –
@HenkHolterman - 你可以看到我以前的帖子,使用waitone ..!我做了一個線程操作,但FuncA被阻塞,直到FuncB處理結果&在FuncA中我正在做一些基於reult的操作,然後我將它發送回主線程。在Marc Gravell的幫助下,我們設法使用Action/delegates/interfaces刪除阻塞。我正在尋找一種方式.net仍然有可能使其無阻塞。你知道任何方式請讓我知道。謝謝。! – Bala