C#中的定时器和线程不能在一起?

Dod*_*bro 2 c# multithreading timer

我只是使用了一些测试,在某些情况下我需要一个线程(再次仅用于测试目的),其中一些我需要一个Timer.

我在做什么或者不能在我的案例中同一个"类"中存在Timer和Thread吗?(Form1.cs的)

我正在导入这些库

using System;
//using System.Threading;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Media;
using System.Collections;
Run Code Online (Sandbox Code Playgroud)

正如你所看到的,我已经评论过System.Threading,因为它不允许我将它与Threading.Tasks一起使用(这让我在这种情况下不存在线程).当我试图取消对Threading的评论时,它不会让我说这是一个暧昧的参考

我做错了什么,或者这是一个C#.NET标准,你不能把它们放在一起吗?

如果是这种情况......为什么Timer和Thread不能在同一个类中

谢谢

ren*_*ene 5

您可以为命名空间设置别名以区分它们

using System;
// other usings
using tAlias = System.Threading;

// use alias
public void Sample()
{
   var thread = new tAlias.Thread( () => { Trace.WriteLine(" demo that thread works"); });
   tAlias.Thread.Sleep(10);
}

// use full namespace 
public void Sample()
{
   var timer = new System.Threading.Timer( () => { Trace.WriteLine(" timer called"); });
   timer.Change(0,5000);
   System.Threading.Thread.Sleep(10);
}
Run Code Online (Sandbox Code Playgroud)

如果两个具有相同名称的类型存在,则编译器(或您)无法确定要使用的类型.来自System.Windows.Form的定时器或来自System.Threading的定时器.这就是命名空间发挥作用的地方.每种类型都存在于自己的命名空间中,您可以使用其完整的namespce名称来查明它们.在代码中将是:

System.Threading.Timer 
Run Code Online (Sandbox Code Playgroud)

要么

System.Windows.Forms.Timer
Run Code Online (Sandbox Code Playgroud)

如果存在歧义,命名空间就会受到拯救.为了让生活更轻松,您可以引入一个别名来减少您必须执行的操作,并且可以使用更少的代码来查看.

因为在Windows窗体类中,很可能您将从System.Windows.Forms命名空间中获得许多类型,您可以使用原样并为"额外"导入的命名空间System.Threading添加别名.


hwc*_*rwe 5

为什么我不能TimerThread同班同学一起使用?

问题是:

Timer两个命名空间中都有一个类:

System.Timers.Timer;
System.Threading.Timer;
Run Code Online (Sandbox Code Playgroud)

因此,如果您只是声明一个计时器,.NET无法确定您要使用哪个计时器:

Timer timer; // Compile Error
Run Code Online (Sandbox Code Playgroud)

您需要更具体,以便编译器知道您要使用哪个计时器:

System.Timers.Timer timer = new System.Timers.Timer();
System.Threading.Timer otherTimer = new System.Threading.Timer(MyCallBackMethod);
Run Code Online (Sandbox Code Playgroud)

如果要将timer类与来自System.Timers组件一起使用,System.Threading可以决定使用命名空间的命名空间别名System.Timers来使代码更具可读性:

using t = System.Timers;

public void MyMethod()
{
   t.Timer = new t.Timer(); 
   // this code is equals to 
   // System.Timers.Timer timer = new System.Timers.Timer();
}
Run Code Online (Sandbox Code Playgroud)