本文整理汇总了C#中System.Threading.AutoResetEvent类的典型用法代码示例。如果您正苦于以下问题:C# AutoResetEvent类的具体用法?C# AutoResetEvent怎么用?C# AutoResetEvent使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
AutoResetEvent类属于System.Threading命名空间,在下文中一共展示了AutoResetEvent类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: Initialize
// Initialize Parallel class's instance creating required number of threads
// and synchronization objects
private void Initialize( )
{
threadsCount = System.Environment.ProcessorCount;
//No point starting new threads for a single core computer
if (threadsCount <= 1) {
return;
}
// array of events, which signal about available job
jobAvailable = new AutoResetEvent[threadsCount];
// array of events, which signal about available thread
threadIdle = new ManualResetEvent[threadsCount];
// array of threads
threads = new Thread[threadsCount];
for ( int i = 0; i < threadsCount; i++ )
{
jobAvailable[i] = new AutoResetEvent( false );
threadIdle[i] = new ManualResetEvent( true );
threads[i] = new Thread( new ParameterizedThreadStart( WorkerThread ) );
threads[i].IsBackground = false;
threads[i].Start( i );
}
}
示例2: AnalysisQueue
internal AnalysisQueue(VsProjectAnalyzer analyzer) {
_workEvent = new AutoResetEvent(false);
_cancel = new CancellationTokenSource();
_analyzer = analyzer;
// save the analysis once it's ready, but give us a little time to be
// initialized and start processing stuff...
_lastSave = DateTime.Now - _SaveAnalysisTime + TimeSpan.FromSeconds(10);
_queue = new List<IAnalyzable>[PriorityCount];
for (int i = 0; i < PriorityCount; i++) {
_queue[i] = new List<IAnalyzable>();
}
_enqueuedGroups = new HashSet<IGroupableAnalysisProject>();
_workThread = new Thread(Worker);
_workThread.Name = "Node.js Analysis Queue";
_workThread.Priority = ThreadPriority.BelowNormal;
_workThread.IsBackground = true;
// start the thread, wait for our synchronization context to be created
using (AutoResetEvent threadStarted = new AutoResetEvent(false)) {
_workThread.Start(threadStarted);
threadStarted.WaitOne();
}
}
示例3: WaitForAll
public WaitForAll(AsyncCallback callbackWhenOver, object asyncState)
{
callbackResults = new Dictionary<string, IAsyncResult>();
this.callbackWhenOver = callbackWhenOver;
this.asyncState = asyncState;
handle = new AutoResetEvent(false);
}
示例4: DemoOne
private static void DemoOne()
{
//AutoResetEvent example
//AutoResetEvent 通知正在等待的线程已发生的事件。
AutoResetEvent waitHandler = new AutoResetEvent(false);//false 即非终止,未触发。
new Thread(() =>
{
waitHandler.WaitOne(); //阻塞当前线程,等待底层内核对象收到信号。
Console.WriteLine("线程1接收到信号,开始处理。");
}).Start();
new Thread(() =>
{
waitHandler.WaitOne(); //阻塞当前线程,等待底层内核对象收到信号。
Console.WriteLine("线程2接收到信号,开始处理。");
}).Start();
new Thread(() =>
{
Thread.Sleep(2000);
Console.WriteLine("线程3发信号");
waitHandler.Set(); //向内核对象发送信号。设置事件对象为非终止状态、false,解除阻塞。
}).Start();
//waitHandler.Close(); //释放句柄资源。
//waitHandler.Reset(); //手动设置事件为非终止状态、false,线程阻止。
Console.ReadLine();
}
示例5: ConsumeMessagesOnMultipleWorkerThreads
public void ConsumeMessagesOnMultipleWorkerThreads()
{
const int NumerOfMessages = 1000;
this.module.ConsumeDelay = TimeSpan.FromMilliseconds(0);
this.testee = new ModuleController();
this.testee.Initialize(this.module, 10);
for (int i = 0; i < NumerOfMessages; i++)
{
this.testee.EnqueueMessage(i);
}
AutoResetEvent signal = new AutoResetEvent(false);
int count = 0;
object padlock = new object();
this.testee.AfterConsumeMessage += delegate
{
lock (padlock)
{
count++;
if (count == NumerOfMessages)
{
signal.Set();
}
}
};
this.testee.Start();
Assert.IsTrue(signal.WaitOne(10000, false), "not all messages consumed. Consumed " + this.module.Messages.Count);
this.testee.Stop();
}
示例6: TestArbitrary
public void TestArbitrary()
{
AutoResetEvent are = new AutoResetEvent(false);
var client = new AustinHarris.JsonRpc.JsonRpcClient(remoteUri);
var arbitrary = new Newtonsoft.Json.Linq.JObject();
JObject r = null;
Exception e = null;
for (int i = 0; i < 10; i++)
{
arbitrary[getPrintableString(10)] = getPrintableString(20);
arbitrary[getNonPrintableString(10)] = getNonPrintableString(20);
arbitrary[getExtendedAsciiString(10)] = getExtendedAsciiString(20);
}
var myObs = client.Invoke<Newtonsoft.Json.Linq.JObject>("testArbitraryJObject", arbitrary, Scheduler.TaskPool);
using(myObs.Subscribe(
onNext: (jo) =>
{
r = jo.Result;
},
onError: _ =>
{
e = _;
},
onCompleted: () => are.Set()
))
{
are.WaitOne();
};
Assert.IsTrue(r.ToString() == arbitrary.ToString());
Assert.IsTrue(e == null);
}
示例7: Engine
/// <summary>
/// Constructs an Engine for the specified Debugger.
/// </summary>
/// <param name="debugger">Debugger instance.</param>
public Engine(Debugger debugger)
{
Debugger = debugger;
_pause = false;
_stop = false;
AllowedToContinue = new AutoResetEvent(false);
}
示例8: GetMarketInfo
private PriceDTO GetMarketInfo(int marketId)
{
IStreamingListener<PriceDTO> listener = null;
PriceDTO marketInfo = null;
try
{
listener = _streamingClient.BuildPricesListener(marketId);
var gate = new AutoResetEvent(false);
listener.MessageReceived += (o, s) =>
{
marketInfo = s.Data;
gate.Set();
};
if (!gate.WaitOne(10000))
{
throw new Exception("timed out waiting for market data");
}
}
finally
{
_streamingClient.TearDownListener(listener);
}
return marketInfo;
}
示例9: ClearMarkedPosts
public static bool ClearMarkedPosts(ThreadMetadata thread, int timeout = CoreConstants.DEFAULT_TIMEOUT_IN_MILLISECONDS)
{
// create request
HttpWebRequest request = AwfulWebRequest.CreateFormDataPostRequest(
"http://forums.somethingawful.com/showthread.php",
"application/x-www-form-urlencoded");
// begin request stream creation and wait...
var signal = new AutoResetEvent(false);
var result = request.BeginGetRequestStream(callback =>
SendClearMarkedPostRequest(callback, signal, thread),
request);
signal.WaitOne();
// begin response stream and wait...
request = result.AsyncState as HttpWebRequest;
result = request.BeginGetResponse(callback => { signal.Set(); }, request);
signal.WaitOne(timeout);
if (!result.IsCompleted)
throw new TimeoutException();
// process the response and return status
bool success = ProcessClearMarkedPostResponse(result);
return success;
}
示例10: BTManager
private bool m_disposed; // Whether or not this manager has been disposed
//--//
/// <summary>
/// Creates and initializes a new BTManager
/// </summary>
protected BTManager(BTDriver driver, IPowerPolicy pp)
{
m_driver = null;
try
{
m_driver = driver;
m_pp = (null == pp) ? new DefaultPowerPolicy() : pp;
m_outstandingConnections = new ArrayList();
m_connectionsToBeProcessed = new ArrayList();
m_newCommand = new AutoResetEvent(false);
m_scheduler = new Thread(new ThreadStart(AggregateAndDispatch));
m_scheduler.Start();
m_disposed = false;
}
catch
{
m_disposed = true;
throw;
}
// Now apply policy for no pending commands
m_pp.ApplyPolicy(m_driver, null, null);
}
示例11: RawSendHelper
private bool RawSendHelper(byte[] aData, bool aWait)
{
if (IsInBackgroundThread)
{
return SendRawData(aData);
}
if (!IsConnected)
{
return false;
}
if (aWait)
{
using (var xEvent = new AutoResetEvent(false))
{
mPendingWrites.Add(new Outgoing {Packet = aData, Completed = xEvent});
while (IsConnected)
{
xEvent.WaitOne(1000);
}
return IsConnected; // ??
}
}
else
{
mPendingWrites.Add(new Outgoing {Packet = aData});
return true;
}
}
示例12: Receive_from_standIn
public void Receive_from_standIn()
{
var cre = PubnubCredentials.LoadFrom("pubnub credentials.txt");
using (var sut = new PubnubHostTransceiver(cre, "hostchannel"))
{
var are = new AutoResetEvent(false);
HostInput result = null;
sut.ReceivedFromStandIn += _ =>
{
result = _;
are.Set();
};
var standIn = new Pubnub(cre.PublishingKey, cre.SubscriptionKey, cre.SecretKey);
var hi = new HostInput{CorrelationId = Guid.NewGuid(), Data = "hello".Serialize(), Portname = "portname", StandInEndpointAddress = "endpoint"};
standIn.publish("hostchannel", hi.Serialize(), _ => { });
Assert.IsTrue(are.WaitOne(5000));
Assert.AreEqual(hi.CorrelationId, result.CorrelationId);
Assert.AreEqual(hi.Data, result.Data);
Assert.AreEqual(hi.Portname, result.Portname);
Assert.AreEqual(hi.StandInEndpointAddress, result.StandInEndpointAddress);
}
}
示例13: Send_to_standIn
public void Send_to_standIn()
{
var cre = PubnubCredentials.LoadFrom("pubnub credentials.txt");
using(var sut = new PubnubHostTransceiver(cre, "hostchannel"))
{
var standIn = new Pubnub(cre.PublishingKey, cre.SubscriptionKey, cre.SecretKey);
try
{
var standInChannel = Guid.NewGuid().ToString();
var are = new AutoResetEvent(false);
ReadOnlyCollection<object> result = null;
standIn.subscribe(standInChannel, (ReadOnlyCollection<object> _) =>
{
result = _;
are.Set();
});
var ho = new HostOutput{CorrelationId = Guid.NewGuid(), Data = "hello".Serialize(), Portname = "portname"};
sut.SendToStandIn(new Tuple<string, HostOutput>(standInChannel, ho));
Assert.IsTrue(are.WaitOne(5000));
var hoReceived = Convert.FromBase64String((string)((JValue)result[0]).Value).Deserialize() as HostOutput;
Assert.AreEqual(ho.CorrelationId, hoReceived.CorrelationId);
Assert.AreEqual(ho.Data, hoReceived.Data);
Assert.AreEqual(ho.Portname, hoReceived.Portname);
}
finally
{
standIn.subscribe("standIn", _ => {});
}
}
}
示例14: GetMethodTableCallTest
public void GetMethodTableCallTest()
{
// ARRANGE
using (AutoResetEvent waitEvent = new AutoResetEvent(false))
{
ResultEventArgs<MethodTable> result = null;
IServerService serverService = new ServerService(new EtsyContext(NetsyData.EtsyApiKey));
serverService.GetMethodTableCompleted += (s, e) =>
{
result = e;
waitEvent.Set();
};
// ACT
serverService.GetMethodTable();
bool signalled = waitEvent.WaitOne(Constants.WaitTimeout);
// ASSERT
// check that the event was fired, did not time out
Assert.IsTrue(signalled, "Not signalled");
// check the data
Assert.IsNotNull(result);
TestHelpers.CheckResultSuccess(result);
Assert.IsTrue(result.ResultValue.Count > 1);
Assert.IsTrue(result.ResultValue.Results.Length > 1);
Assert.IsNull(result.ResultValue.Params);
}
}
示例15: GetMethodTableApiKeyInvalidTest
public void GetMethodTableApiKeyInvalidTest()
{
// ARRANGE
using (AutoResetEvent waitEvent = new AutoResetEvent(false))
{
ResultEventArgs<MethodTable> result = null;
IServerService serverService = new ServerService(new EtsyContext("InvalidKey"));
serverService.GetMethodTableCompleted += (s, e) =>
{
result = e;
waitEvent.Set();
};
// ACT
serverService.GetMethodTable();
bool signalled = waitEvent.WaitOne(Constants.WaitTimeout);
// ASSERT
// check that the event was fired, did not time out
Assert.IsTrue(signalled, "Not signalled");
// check the data - should fail
Assert.IsNotNull(result);
Assert.IsNotNull(result.ResultStatus);
Assert.IsFalse(result.ResultStatus.Success);
Assert.AreEqual(WebExceptionStatus.ProtocolError, result.ResultStatus.WebStatus);
}
}