问题描述
美好的一天,
我这里有一个相当简单的问题。我是线程的新手,想知道是否在我的下面的场景中使用它。
基本上我有一个尚未测试的C#程序。程序运行时,它会使用对服务器的API调用向不同的手机发送批量短信。发送需要对发送到的每个号码进行呼叫。这显然意味着一个foreach循环。
我的第一个问题是:
当程序执行此代码时,它是否会锁定主该程序的窗口,并阻止用户对该程序进行其他工作?用户是否需要等待发送完成?
第二个问题:
我应该使用一个线程来运行该方法吗?背景还是我误解了线程的重点?在没有表格锁定的情况下还有另一种方法吗?
如果这些是简单的问题,请原谅我,但想简单地学习并找到更多的见解。
问候
我尝试过:
我试过阅读有关线程的文章,但无法弄清楚这是否正是我需要的
是的。是的。
是的,不,你不是误会。并且没有。
可能,我设置了一个线程来进行实际发送,并从Queue< T>中提供它。通过锁。如果队列中有某些内容,则线程获取它,处理它并再次检查。当它为空时,线程会进入休眠状态一秒钟或一分钟然后再次检查。
OG有点短,答案很长,任何需要I / O操作的操作 - 包括但不限于网络I / O,磁盘I / O等甚至加载图像位图将是一个原因 - 总是会导致您的应用程序冻结。这是因为控件已转移到控制I / O操作的程序集,您的应用程序必须等待该操作完成才能实际执行其他操作,例如尤其处理用户交互。大多数情况下,解决方案只是以下函数结构的一种情况,
public async void IOFunction(){
// 代码..
// 几乎每个对象在.NET和WinRT中具有异步功能
await Obj.DoJobAsync();
// 代码。
}
这样,您将能够处理用户交互并仍然在后端执行I / O任务。这类似于特殊的,线程
,任务
或 BackgroundWorker
对象,但以更简单的方式。
更多信息: [ ^ ]
OG所说的是准确的,但我不建议仅依赖于此。而不是那样,我建议你自己不要使用 Thread
。而不是那样,只需使用任务
对象。我的建议是简单地采用异步/等待编程模式。无需深入 Thread
,或使用任务
或使用 BackgroundWorker
对象或为此创建自己的机制。 C#处理异步任务的方式非常方便,自从我开始使用它以来,我个人很享受我的生活。
免责声明:由于双功能声明结构,异步/等待模式对于初学者来说真的很难。但是一旦你理解了它,它对你来说将是惊人的。忘记线程,你根本不必使用它们。
Good day,
I have a rather simple question here. I am new to threads and was wondering whether to use it with my below scenario.
Basically I have a C# program that is not tested yet. When the program runs, it will send bulk sms messages to different cellphones using API calls to a server. The sending requires the call to be made for each number being sent to. This obviously means a foreach loop.
My first question is this:
When the program executes this code, will it lock up the main window of the program and prevent the user from doing other work on the program? Will the user need to wait for the sending to complete?
Second Question:
Should I use a Thread to run the method in the background or am I misunderstanding the point of a Thread? Is there another way of doing this without the form locking up?
Forgive me if these are simple questions, but simple seeking to learn and find more insight in this.
Regards
What I have tried:
I have tried reading through articles about threads, but cannot figure out whether this is exactly what I need
Yes. And yes.
Yes, and no, you're not misunderstanding. And no.
Probably, I'd set up a thread to do the actual sending, and feed it from a Queue<T> via a lock. If there is something in the queue, the thread gets it, deals with it and checks again. When it's empty, the thread goes to sleep for a second or a minute and then checks again.
"
"
Try this:
private void myButton_Click(object sender, EventArgs e) { Thread worker1 = new Thread(MyMethod); worker1.Start("Hello"); Thread worker2 = new Thread(MyMethod); worker2.Start("Hello There"); Thread worker3 = new Thread(MyMethod); worker3.Start("Hello There Again"); } private void MyMethod(object message) { string s = message as string; if (s != null) { Console.WriteLine(s); Thread.Sleep(5000); Console.WriteLine("{0} - Completed", s); } }
It kicks off three threads which do the same thing with different data.
And you get something like this:
Hello Hello There Hello There Again The thread 0x15c8 has exited with code 259 (0x103). The thread 0x7ac has exited with code 259 (0x103). The thread 0x1e2c has exited with code 259 (0x103). Hello - Completed Hello There Again - Completed Hello There - Completed
I don't suggest that you do it that way - you need to send the messages one after the other not try to send them all at once since you've only got the one device to send them. So you need a single extra thread with a loop in it instead, but that should give you an idea.
Note that in this example, the threads didn't finish in the order they were started - that's to be expected since Windows is a multi tasking system.
OG was a bit short, the long answer is, any operation that requires an I/O operation — including but not limited to network I/O, disk I/O etc. even loading the image bitmaps would be a reason here — would always cause your application to freeze. That is because the control has been transferred to the assembly that controls I/O operation and your application will have to wait for that operation to complete before it can actually perform other operations such as "and especially" handling user interaction. Mostly, the solution is simply a case of the following function-structure,
public async void IOFunction() { // Code.. // Almost every object has async functionality in .NET and WinRT await Obj.DoJobAsync(); // Code. }
This way, you will be able to handle the user interaction and still perform I/O task at the backend. That is similar to having special, Thread
, Task
or BackgroundWorker
objects but in a much simpler way.
For more: Asynchronous Programming with async and await (C#)[^]
What OG said is accurate, but I don't recommend relying on that only. Instead of that, I would recommend not-to-use Thread
yourself. Instead of that, just use a Task
object. My recommendation is to simply embrace async/await pattern of programming. There is no need to go in the depths of Thread
, or using Task
or using BackgroundWorker
object or to create your own mechanism for this. C#'s way of handling asynchronous tasks is really handy and I have personally enjoyed my life ever since I started using it.
Disclaimer: Async/await pattern is really tough for beginners because of bi-function-declaration structure. But once you understand it, it will be amazing for you. Forget about threads, you don't have to use them at all.
这篇关于关于线程的问题以及是否有必要。的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!