在C#中实现独立操作 [英] Implementing independent operations in C#
问题描述
我有以下情况. 我有一个在线程T1中运行的操作A.现在,我要做的是从该线程T1启动另一个操作,比如说B,但是我希望B独立于A和T1,即,在启动操作B之后,T1应该继续执行其操作并在B终止时终止可以继续进行这项工作,直到完成工作为止(无论T1是否终止).
I have the following situation. I have an operation A running in a thread, say, T1. Now what I want to do is to launch another operation, say B from this thread T1 but I want B to be independent of A and T1, i.e., after launching operation B, T1 should continue to do what it was doing and terminate while B can continue to do it's work until it's work is finished (irrespective of whether T1 has terminated or not).
我希望B完全独立于T1或A,并且应该允许T1终止,而与B的当前状态无关.
I want B to be completely independent of T1 or A and should allow T1 to terminate irrespective of B's current state.
我正在使用.net 4.0而不是.net 4.5
I am using .net 4.0 and not .net 4.5
有什么建议吗?
提前谢谢.
推荐答案
我建议您使用Tasks
而不是线程.这是代码
i would suggest you to use Tasks
instead of threads. here is code
internal class Program
{
private static void Main(string[] args)
{
// starting your thread A
Task.Factory.StartNew(ThreadAWork);
Console.ReadKey();
}
// Thread A's method
private static void ThreadAWork()
{
Console.WriteLine("Thread:A Started");
// starting Thread B from Thread A
Task.Factory.StartNew(ThreadBWork);
Thread.Sleep(1000);
Console.WriteLine("Thread:A Stopped");
}
// Thread B's method
private static void ThreadBWork()
{
Console.WriteLine("Thread:B Started");
Thread.Sleep(2000);
Console.WriteLine("Thread:B Stopped");
}
}
这篇关于在C#中实现独立操作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!