为多条文本消息C#添加时间延迟



如果字符超过136,我们希望将消息拆分为多条(短信)文本消息。

但我们也希望确保第二条消息在第一条消息之后、第三条消息之前到达。

到目前为止,从我们所做的为数不多的测试来看,它似乎是这样工作的,但为了确保我们仍然希望增加大约3秒的延迟

Thread.Sleep是正确的方法吗?或者除了添加延迟之外还有其他解决方案吗?

这是代码:

    // Split message to send them as individual text messages
    string[] messages = splitMessage(request["message"], 132);
    for (int i = 0; i < messages.Length; i++)
    {
        HttpWebRequest _wr = (HttpWebRequest)WebRequest.Create(url);
        // Use the CredentialCache so you can attach the authentication to the request
        CredentialCache mycache = new CredentialCache { { new Uri(url), "Basic", new NetworkCredential(_username, _password) } };
        // use Basic Authentication
        _wr.Credentials = mycache;
        _wr.Method = "POST";
        _wr.ContentType = "application/json";
        _wr.Timeout = -1;   // not sure if necessary but it's not harmful
        // _data variable holds the data to be pushed to the server in the request.
        // this piece of data holds the request to send a text message from the application
        string _data = "{"outboundSMSMessageRequest":" +
                        "{"address": "" + formatedAddress + "","requestId": "" + request["requestId"] + """ +
                        ","outboundSMSTextMessage": "" + messages[i] + "","senderAddress": "" + request["sender"] + """ +
                        _optional + "}}";
        //get a reference to the request-stream, and write the POST data (_data) to it
        using (var s = new StreamWriter(_wr.GetRequestStream()))
        {
                s.Write(_data);
        }
        //get response-stream, and use a streamReader to read the content
        try
        {
                HttpWebResponse _response = (HttpWebResponse)_wr.GetResponse();
        }
        catch (WebException ex)
        {
                using (StreamWriter file = new StreamWriter(@"D:WEBSMSjsonResponse.txt", true))
                {
                        file.WriteLine("No good");
                }
                // Log exception and throw as for GET example above
                Trace.WriteLine("No good");
                Trace.WriteLine(ex);
        }
        using (Stream s = _wr.GetResponse().GetResponseStream())
        {
                using (StreamReader sr = new StreamReader(s))
                {
                        var jsonData = sr.ReadToEnd();
                        Trace.WriteLine("Server response: " + jsonData);
                        //decode jsonData with javascript serializer
                        using (StreamWriter file = new StreamWriter(@"D:WEBSMSjsonResponse.txt", true))
                        {
                                file.WriteLine("Server response: " + jsonData);
                        }
                }
        }
}

我更愿意查看短信发送者API的文档,因为那里可能写着他们不能保证短信的顺序-他们可以有内部队列,来自服务器的响应可能意味着他们已经将消息排入队列,而不是他们已经发送了消息。在这种情况下,添加3、5甚至10秒的延迟是没有帮助的。

最新更新