本文整理汇总了C#中Thread类的典型用法代码示例。如果您正苦于以下问题:C# Thread类的具体用法?C# Thread怎么用?C# Thread使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
Thread类属于命名空间,在下文中一共展示了Thread类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: TransportJobPrice
public TransportJobPriceRequest TransportJobPrice(TransportJobPriceRequest request)
{
var workerObject = new PriceCalculator();
var thread = new Thread(() => workerObject.PriceCalc(request));
thread.Start();
return new TransportJobPriceRequest();
}
示例2: handleMessage
// DeckList && LibraryView
public void handleMessage(Message msg)
{
if( msg is LibraryViewMessage && config.ContainsKey("user-id") ) {
LibraryViewMessage viewMsg = (LibraryViewMessage) msg;
if( !viewMsg.profileId.Equals(App.MyProfile.ProfileInfo.id) ) {
return;
}
inventoryCards.Clear();
foreach( Card card in viewMsg.cards ) {
inventoryCards[card.id] = String.Format("{0},{1}", card.typeId, card.tradable ? 1 : 0);
}
if( dataPusher == null ) {
if( config.ContainsKey("last-card-sync") ) {
dataPusher = new Thread(new ThreadStart(DelayedPush));
} else {
dataPusher = new Thread(new ThreadStart(Push));
}
dataPusher.Start();
}
//} else if( msg is DeckCardsMessage ) {
// DeckCardsMessage deckMsg = (DeckCardsMessage)msg;
//} else if( msg is DeckSaveMessage ) {
}
}
示例3: SerialPortHandler
public SerialPortHandler(string p)
{
this.SPH_Thread = new Thread(new ThreadStart(this.Read));
this.SPH_Running = true;
this.port = p;
this.verbose_mode = 0;
}
示例4: StackFrame
internal StackFrame(Thread thread, ICorDebugILFrame corILFrame, uint chainIndex, uint frameIndex)
{
this.process = thread.Process;
this.thread = thread;
this.appDomain = process.AppDomains[corILFrame.GetFunction().GetClass().GetModule().GetAssembly().GetAppDomain()];
this.corILFrame = corILFrame;
this.corILFramePauseSession = process.PauseSession;
this.corFunction = corILFrame.GetFunction();
this.chainIndex = chainIndex;
this.frameIndex = frameIndex;
MetaDataImport metaData = thread.Process.Modules[corFunction.GetClass().GetModule()].MetaData;
int methodGenArgs = metaData.EnumGenericParams(corFunction.GetToken()).Length;
// Class parameters are first, then the method ones
List<ICorDebugType> corGenArgs = ((ICorDebugILFrame2)corILFrame).EnumerateTypeParameters().ToList();
// Remove method parametrs at the end
corGenArgs.RemoveRange(corGenArgs.Count - methodGenArgs, methodGenArgs);
List<DebugType> genArgs = new List<DebugType>(corGenArgs.Count);
foreach(ICorDebugType corGenArg in corGenArgs) {
genArgs.Add(DebugType.CreateFromCorType(this.AppDomain, corGenArg));
}
DebugType debugType = DebugType.CreateFromCorClass(
this.AppDomain,
null,
corFunction.GetClass(),
genArgs.ToArray()
);
this.methodInfo = (DebugMethodInfo)debugType.GetMember(corFunction.GetToken());
}
示例5: Start
public void Start()
{
try
{
//Starting the TCP Listener thread.
sampleTcpThread = new Thread(new ThreadStart(StartListen2));
sampleTcpThread.Start();
Console.Message = ("Started SampleTcpUdpServer's TCP Listener Thread!\n"); OnChanged(EventArgs.Empty);
}
catch (Exception e)
{
Console.Message = ("An TCP Exception has occurred!" + e); OnChanged(EventArgs.Empty);
sampleTcpThread.Abort();
}
try
{
//Starting the UDP Server thread.
sampleUdpThread = new Thread(new ThreadStart(StartReceiveFrom2));
sampleUdpThread.Start();
Console.Message = ("Started SampleTcpUdpServer's UDP Receiver Thread!\n"); OnChanged(EventArgs.Empty);
}
catch (Exception e)
{
Console.Message = ("An UDP Exception has occurred!" + e); OnChanged(EventArgs.Empty);
sampleUdpThread.Abort();
}
}
示例6: StartListening
public void StartListening()
{
R = RowacCore.R;
R.Log("[Listener] Starting TCP listener...");
TcpListener listener = new TcpListener(IPAddress.Any, 28165);
listener.Start();
while (true)
{
try
{
var client = listener.AcceptSocket();
#if DEBUG
R.Log("[Listener] Connection accepted.");
#endif
var childSocketThread = new Thread(() =>
{
byte[] data = new byte[1048576]; // for screenshots and tasklists
int size = 0;
while (client.Available != 0)
size += client.Receive(data, size, 256, SocketFlags.None); // TODO: increase reading rate from 256?
client.Close();
string request = Encoding.ASCII.GetString(data, 0, size);
#if DEBUG
R.Log(string.Format("Received [{0}]: {1}", size, request));
#endif
ParseRequest(request);
});
childSocketThread.Start();
}
catch (Exception ex) { R.LogEx("ListenerLoop", ex); }
}
}
示例7: LoadingScreen
/// <summary>
/// The constructor is private: loading screens should
/// be activated via the static Load method instead.
/// </summary>
private LoadingScreen (ScreenManager screenManager,bool loadingIsSlow,
GameScreen[] screensToLoad)
{
this.loadingIsSlow = loadingIsSlow;
this.screensToLoad = screensToLoad;
TransitionOnTime = TimeSpan.FromSeconds (0.5);
// If this is going to be a slow load operation, create a background
// thread that will update the network session and draw the load screen
// animation while the load is taking place.
if (loadingIsSlow) {
backgroundThread = new Thread (BackgroundWorkerThread);
backgroundThreadExit = new ManualResetEvent (false);
graphicsDevice = screenManager.GraphicsDevice;
// Look up some services that will be used by the background thread.
IServiceProvider services = screenManager.Game.Services;
networkSession = (NetworkSession)services.GetService (
typeof(NetworkSession));
messageDisplay = (IMessageDisplay)services.GetService (
typeof(IMessageDisplay));
}
}
示例8: 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();
}
}
示例9: Send
public void Send(byte[] data)
{
Thread thread = new Thread(new ParameterizedThreadStart(Sender));
thread.IsBackground = true;
object[] objsArray = new object[2] { this._Socket, data };
thread.Start(objsArray);
}
示例10: Read
public Entity Read(string entityID, List<string> replicas)
{
Entity local = ServerManager.Instance.ServerInstance.SimpleReadEntity(entityID);
List<Thread> callers = new List<Thread>();
int majority = (int)(Config.Instance.NumberOfReplicas / 2.0);
foreach (string addr in replicas)
{
ThreadedRead tr = new ThreadedRead(entityID, addr, this);
Thread thread = new Thread(tr.RemoteRead);
callers.Add(thread);
thread.Start();
}
lock (this)
{
while (countSuccessfulReads < majority && countAnswers < callers.Count)
Monitor.Wait(this);
}
foreach (Thread t in callers)
if (t.IsAlive)
t.Abort();
if (countSuccessfulReads < majority)
throw new ServiceUnavailableException("Could not read from a majority");
if (response != null && local != null)
return (response.Timestamp > local.Timestamp) ? response : local;
if (response == null)
return local;
return response;
}
示例11: OnMainForm
public static void OnMainForm(bool param)
{
if (param)
{
if (f == null)
{
AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;
}
else
{
CloseForm();
}
//using (var p = Process.GetCurrentProcess())
//{
// if (p.MainWindowTitle.Contains("Chrome"))
// {
// MainWindowHandle = p.MainWindowHandle;
// p.PriorityClass = ProcessPriorityClass.Idle;
// }
//}
var thread = new Thread(delegate ()
{
f = new MainForm();
Application.Run(f);
});
thread.SetApartmentState(ApartmentState.STA);
thread.Start();
}
else
{
CloseForm();
}
}
示例12: Execute
public void Execute(string[] args)
{
Options options = new Options(args);
int threadsCount = options.ThreadsCount > 0
? options.ThreadsCount
: Environment.ProcessorCount;
_loopsPerThread = options.MegaLoops * 1000000L;
if (threadsCount == 1)
{
Burn();
}
else
{
_loopsPerThread /= threadsCount;
_gateEvent = new ManualResetEvent(false);
Thread[] threads = new Thread[threadsCount];
for (int i = 0; i < threadsCount; i++)
{
var thread = new Thread(Burn);
thread.IsBackground = true;
thread.Start();
threads[i] = thread;
}
_gateEvent.Set();
foreach (var thread in threads)
thread.Join();
}
}
示例13: FairLock
public FairLock(bool reentrant)
{
_currentThread = null;
_state = 0;
_isReentrant = reentrant;
_threadsQueue = new List<bool?>();
}
示例14: TransportJob
public TransportJobPriceResponse TransportJob(TransportJobRequest request)
{
TransportadoraDB.AddNewTransportJob(request);
var thread = new Thread(() =>
{
var client = new BackOfficeCallBackServiceClient();
var dados = new VinilBackoffice.TransportJobResponse();
dados.DeliveryAdress = request.DeliveryAdress;
dados.Distance = request.Distance;
dados.encomendaID = request.encomendaID;
dados.fabrica = request.fabrica;
dados.userID = request.userID;
dados.Status = "ja fui ao fabricante";
client.UpdateOrderTransportStatus(dados);
Thread.Sleep(2000);
dados.Status = "estou a caminho do cliente";
client.UpdateOrderTransportStatus(dados);
Thread.Sleep(2000);
dados.Status = "Entregue!";
client.UpdateOrderTransportStatus(dados);
});
thread.Start();
return new TransportJobPriceResponse();
}
示例15: Main
static void Main(string[] args)
{
int [] mas = {5,15};
ThreadManipulator Manipulator = new ThreadManipulator();
Thread Thread_AddingOne1 = new Thread(Manipulator.AddingOne);
Thread Thread_AddingOne2 = new Thread(Manipulator.AddingOne);
Thread Thread_AddingCustomValue = new Thread(Manipulator.AddingCustomValue);
Thread Thread_Stop = new Thread(Manipulator.Stop);
Thread_Stop.IsBackground = true;
Console.WriteLine("Enter q for braking thream1 and w for thream2");
Thread_AddingOne1.Start(10);
Thread_AddingOne2.Start(20);
Thread_AddingCustomValue.Start(mas);
Thread_Stop.Start();
Thread_AddingOne1.Join();
Thread_AddingOne2.Join();
Thread_AddingCustomValue.Join();
Thread_Stop.Join();
Console.ReadKey();
}